Skip to content
Open
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
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ AGENTFLOW_PLATFORM_MCP_URL=
# Optional model IDs available to your CodeBuddy account (comma-separated):
AGENTFLOW_ASSISTANT_MODELS=
AGENTFLOW_ASSISTANT_MODEL=
# Optional path to administrator-verified SSH host keys. See docs/deployment.md.
# Optional platform path to administrator-verified SSH host keys. See docs/deployment.md.
AGENTFLOW_GIT_SSH_KNOWN_HOSTS=
# Worker separation, installed runners and preview settings retain AGENTFLOW_ names.
# See docs/deployment.md. Production HTTPS: AGENTFLOW_SECURE_COOKIES=true.
2 changes: 1 addition & 1 deletion docs/conversation-workspaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

- HTTPS:个人配置的 Git Token。`GIT_ASKPASS` 指向工作区 `.agentflow/runtime/git-askpass-hosts`,脚本本身不含令牌,从提示里解析出 URL 主机,只在它恰好是 `https://github.com` 时以 `x-access-token` 应答;`github.com.example`、`github.com@example`、`http://` 等其他地址都拿不到凭据。带 `oauth2:`/`private:` 前缀的令牌不是 GitHub 令牌,不会注入。`GIT_TERMINAL_PROMPT=0`,不会卡在交互输入上。
- `GH_TOKEN`:同一个令牌,供 `gh` 或 `curl` 调 GitHub API。平台进程自身的 `GH_TOKEN`/`GITHUB_TOKEN` 不会透传进沙箱。
- SSH:个人 SSH 密钥按 `host:port` 绑定(不再按项目登记的仓库地址),任何克隆地址只要主机端口匹配就能用。私钥只在平台进程内存中的临时 ssh-agent 里,沙箱只看到 agent socket、公钥与 ssh config;主机公钥必须固定:平台内置 GitHub 公布的 `github.com:22` 与 `ssh.github.com:443` 公钥(来自 api.github.com/meta),其他主机由管理员通过 `AGENTFLOW_GIT_SSH_KNOWN_HOSTS` 固定,两者合并生效(文件里的 `@revoked` 同样作用于内置公钥);未固定的主机报错说明原因。
- SSH 克隆使用按 `host:port` 绑定的个人密钥。同一主机和端口的仓库共用该密钥。执行进程在内存中持有私钥,并通过临时 ssh-agent 签名。沙箱只接收 agent socket、公钥与 SSH 配置。平台内置 `github.com:22` 与 `ssh.github.com:443` 的主机公钥,其他主机由管理员通过 `AGENTFLOW_GIT_SSH_KNOWN_HOSTS` 配置。Runner 0.11.1 及以上会在启动工作区会话时收到匹配的条目。平台条目优先,本地 Runner 配置可补充其他主机和端口,两处的 `@revoked` 条目都生效。
- 提交身份:`GIT_CONFIG_SYSTEM` 设为发言人的登录名,邮箱 `<login>@users.noreply.loopforge.invalid`;Agent 可以用 `git config --global/--local` 覆盖。

工具结果和回复都会对发言人的令牌(含去掉前缀后的裸令牌)做脱敏;提示词要求 Agent 不打印、不回显、不写入令牌。
Expand Down
3 changes: 2 additions & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ A clone that is stopped this way is not retried, since a retry would wait on the
Use Git SSH for GitLab.com, self-managed GitLab, Gitea, Gogs, GitHub, and other Git hosts that offer this transport. In **Project settings → Code repositories** or **Quick access**, enter the clone address, such as `git@gitlab.com:group/repo.git` or `ssh://git@git.example.org:2222/group/repo.git`, and select the existing default branch. GitHub HTTPS continues to use GitHub authorization or a PAT.

1. GitHub (`github.com:22` and `ssh.github.com:443`) works without configuration: LoopForge pins the host keys GitHub publishes at `api.github.com/meta`. For any other host, the deployment administrator creates a dedicated OpenSSH `known_hosts` file; its entries, including `@revoked`, are combined with the built-in GitHub keys. Verify the host keys against the provider's published fingerprints or with the server administrator before adding them. Use exact hostnames or IP addresses, with `[host]:port` for a nondefault port. Wildcards and hashed entries do not grant access. For a trusted team deployment, add internal hosts explicitly to this same file.
2. For hosts other than GitHub, set `AGENTFLOW_GIT_SSH_KNOWN_HOSTS` to the file's absolute path on the platform, workers and execution machines. For Compose, put it under the existing `LOOPFORGE_DATA_DIR` bind mount and set the absolute path in `.env`. Install Git and the OpenSSH client on execution machines and in custom sandbox images. Upgrade execution machines to Runner **0.9.3** or later. Docker sandbox commands need the sandbox and execution process to share the Linux kernel for the signing agent socket. With a Docker VM separate from a native runner, use managed checkout and delivery, or use a native sandbox for interactive Git commands.
2. Set `AGENTFLOW_GIT_SSH_KNOWN_HOSTS` to the file's absolute path on the platform. For Compose, put the file under the existing `LOOPFORGE_DATA_DIR` bind mount and set the absolute path in `.env`. Runner **0.11.1** and later receive the matching host entries when a task or workspace request needs Git SSH. The encoded entries have a 1 MiB allowance per dispatch. Platform entries take precedence for the same host and port. Runner-local entries supply pins for other endpoints, and `@revoked` entries from both sources apply. Runners **0.9.3** through **0.11.0** still need their own file and variable. Configure the variable on any separate worker that connects to the SSH host directly.
Install Git and the OpenSSH client on execution machines and in custom sandbox images. Docker sandbox commands need the sandbox and execution process to share the Linux kernel for the signing agent socket. With a Docker VM separate from a native runner, use managed checkout and delivery, or use a native sandbox for interactive Git commands.
3. Generate dedicated SSH keys with no passphrase for unattended execution. Add each public key to your hosting account and grant access to the repositories it needs. Grant write access if the run must push. Under **Personal settings → Git SSH keys**, add one private key per SSH host, such as `gitlab.com` or `git.example.org:2222`. An omitted port means 22. Edit that host's entry to replace its key.

Repositories automatically use the current user's key for their SSH host and port; repositories on the same host and port share that key. The repository form only shows a red warning when that host has no personal key. This reminder does not block saving the repository or completing setup; credentials and host trust can be configured before the first Git operation. There is no repository-specific or default fallback key. Checkout and SOP execution use the responsible user's keys. Conversation submission and the workspace terminal use the requesting user's keys. The temporary signing agent closes when the command or terminal ends. A terminal's agent never lives in the shared workspace: with the `bwrap` driver it sits in a private directory bound only into that terminal, and with the `local` driver (no isolation) it stays outside the workspace in a 0700 directory. Docker and seatbelt workspaces share one filesystem view among all their processes, so their terminals get no personal SSH key; push from there with the platform's submit action. `git@github.com:` and `ssh://git@github.com/` addresses are saved as GitHub repositories (HTTPS + token, automatic pull requests) unless `provider` is explicitly `ssh`. To rotate a key, replace it in settings and revoke the old public key at the host.
Expand Down
6 changes: 6 additions & 0 deletions internal/domain/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ func (r Runner) SupportsGitHTTP() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionGitHTTP)
}

// RunnerVersionGitSSHKnownHosts is the first runner to accept platform SSH pins.
const RunnerVersionGitSSHKnownHosts = "0.11.1"

func (r Runner) SupportsSharedPush() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionSharedPush)
}
Expand Down Expand Up @@ -376,6 +379,8 @@ type RunnerTask struct {
RunID string `json:"runId,omitempty"`
NodeID string `json:"nodeId,omitempty"`
Invocation *RunnerInvocation `json:"invocation,omitempty"`
// GitSSHKnownHosts is attached on authenticated claim and is never queued.
GitSSHKnownHosts *GitSSHKnownHosts `json:"gitSshKnownHosts,omitempty"`
// Sandbox is the workflow sandbox definition resolved by the control
// plane. The runner creates it locally so Docker/seatbelt/bwrap isolation
// lives on the same machine that executes the Agent CLI.
Expand Down Expand Up @@ -435,6 +440,7 @@ type RunnerSandboxSpec struct {
// PublicRunnerTask strips task-scoped credentials from management responses.
// The authenticated claiming runner receives the original task payload.
func PublicRunnerTask(task RunnerTask) RunnerTask {
task.GitSSHKnownHosts = nil
if task.PreviewArchive != nil {
copySpec := *task.PreviewArchive
copySpec.UploadToken = ""
Expand Down
15 changes: 15 additions & 0 deletions internal/domain/runner_workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,22 @@ const (
RunnerWorkspaceOperationCheckouts = "checkouts"
RunnerWorkspaceOperationMaintenance = "maintenance"
RunnerWorkspaceOperationLoginModels = "login_models"
RunnerWorkspaceOperationConversationCLI = "conversation_process"
)

// RunnerSSHKnownHostsWireLimit is the encoded allowance for the optional
// known_hosts field in a runner task claim.
const RunnerSSHKnownHostsWireLimit = 1 << 20

// GitSSHKnownHosts carries the platform's scoped SSH host keys over an
// authenticated runner transport. Configuration errors are also sent so the
// runner can fail closed when the platform cannot supply the configured pins.
type GitSSHKnownHosts struct {
Entries string `json:"entries,omitempty"`
ReadFailed bool `json:"readFailed,omitempty"`
TooLarge bool `json:"tooLarge,omitempty"`
}

// RunnerWorkspaceRequest is a bounded workspace request sent over the
// runner's outbound control socket. Responses are transient and are never
// persisted in runner_tasks or the run record.
Expand Down Expand Up @@ -63,6 +77,7 @@ type RunnerWorkspaceRequest struct {
Terminal *WorkspaceTerminalRequest `json:"terminal,omitempty"`
TerminalOwner int64 `json:"terminalOwner,omitempty"`
TerminalGitSSHKeys map[string]string `json:"terminalGitSshKeys,omitempty"`
GitSSHKnownHosts *GitSSHKnownHosts `json:"gitSshKnownHosts,omitempty"`
// TerminalGitHTTPCredentials belongs to TerminalOwner and is sent only on open.
TerminalGitHTTPCredentials map[string]GitHTTPExecutionCredential `json:"terminalGitHttpCredentials,omitempty"`
// WorkspaceRunID selects the shared checkout owner; RunID continues to
Expand Down
57 changes: 7 additions & 50 deletions internal/gitwork/ssh.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package gitwork

import (
"bytes"
"context"
"crypto/sha256"
"errors"
Expand Down Expand Up @@ -64,48 +63,6 @@ github.com,[ssh.github.com]:443 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAy
github.com,[ssh.github.com]:443 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=
`

func sshHostKeys(remotes []SSHRemote) ([]byte, error) {
content := []byte(builtinKnownHosts)
if path := strings.TrimSpace(os.Getenv(SSHKnownHostsEnv)); path != "" {
configured, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("无法读取 %s 指定的主机密钥文件", SSHKnownHostsEnv)
}
// Configured entries come first so an @revoked line still applies.
content = append(append(configured, '\n'), content...)
}
allowed := make(map[string]bool, len(remotes))
for _, remote := range remotes {
allowed[knownhosts.Normalize(net.JoinHostPort(remote.Host, remote.Port))] = false
}
var pinned bytes.Buffer
for _, line := range bytes.Split(content, []byte("\n")) {
marker, hosts, key, _, _, err := ssh.ParseKnownHosts(line)
if err != nil || (marker != "" && marker != "revoked" && marker != "cert-authority") {
continue
}
for _, host := range hosts {
host = strings.ToLower(host)
if _, ok := allowed[host]; !ok {
continue
}
if marker != "" {
fmt.Fprintf(&pinned, "@%s ", marker)
}
fmt.Fprintf(&pinned, "%s %s", host, ssh.MarshalAuthorizedKey(key))
if marker != "revoked" {
allowed[host] = true
}
}
}
for _, remote := range remotes {
if endpoint := knownhosts.Normalize(net.JoinHostPort(remote.Host, remote.Port)); !allowed[endpoint] {
return nil, fmt.Errorf("SSH 主机 %s 未获信任:平台只内置了 github.com 的公钥,其他主机请管理员在 %s 中添加并核对该主机和端口的公钥", endpoint, SSHKnownHostsEnv)
}
}
return pinned.Bytes(), nil
}

// sshBinding ties one repository remote to its host alias and private key.
type sshBinding struct {
remote SSHRemote
Expand Down Expand Up @@ -155,22 +112,22 @@ func bindSSHRemotes(environment map[string]string, keys map[string]string) ([]ss
// Aliases bind each repository to its selected host key.
// The filesystem contains a socket and public data only. clientRoot is the
// mount path corresponding to root for a client in a container.
func StartSSH(environment map[string]string, keys map[string]string, root, clientRoot string) (func(), error) {
func StartSSH(ctx context.Context, environment map[string]string, keys map[string]string, root, clientRoot string) (func(), error) {
if len(keys) == 0 {
return func() {}, nil
}
bindings, remotes, err := bindSSHRemotes(environment, keys)
if err != nil {
return nil, err
}
return startSSHSession(environment, bindings, remotes, root, clientRoot)
return startSSHSession(ctx, environment, bindings, remotes, root, clientRoot)
}

// StartSSHHosts gives every SSH remote on the given hosts the matching key,
// without knowing the repositories in advance: an agent that clones
// git@github.com:org/repo.git itself gets the requester's github.com key.
// keys maps "host:port" endpoints (as stored per user) to private keys.
func StartSSHHosts(environment map[string]string, keys map[string]string, root, clientRoot string) (func(), error) {
func StartSSHHosts(ctx context.Context, environment map[string]string, keys map[string]string, root, clientRoot string) (func(), error) {
endpoints := make([]string, 0, len(keys))
for endpoint, key := range keys {
if strings.TrimSpace(key) != "" {
Expand All @@ -193,17 +150,17 @@ func StartSSHHosts(environment map[string]string, keys map[string]string, root,
bindings = append(bindings, sshBinding{remote: remote, alias: fmt.Sprintf("lf-%x", sum[:16]), key: keys[endpoint], match: remote.Host})
remotes = append(remotes, remote)
}
return startSSHSession(environment, bindings, remotes, root, clientRoot)
return startSSHSession(ctx, environment, bindings, remotes, root, clientRoot)
}

func startSSHSession(environment map[string]string, bindings []sshBinding, remotes []SSHRemote, root, clientRoot string) (func(), error) {
func startSSHSession(ctx context.Context, environment map[string]string, bindings []sshBinding, remotes []SSHRemote, root, clientRoot string) (func(), error) {
environment["GIT_SSH_VARIANT"] = "ssh"
if len(bindings) == 0 {
// Keep terminals usable for editing without using a host identity.
environment["GIT_SSH_COMMAND"] = `sh -c 'echo "未配置 Git SSH 密钥,请在个人配置中添加" >&2; exit 1' --`
return func() {}, nil
}
pinned, err := sshHostKeys(remotes)
pinned, err := sshHostKeys(ctx, remotes)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -374,7 +331,7 @@ func sshCommandEnvironment(ctx context.Context, args []string) (map[string]strin
return nil, nil, fmt.Errorf("%s: %w", remote, ErrSSHKeyRequired)
}
env := make(map[string]string)
cleanup, err := StartSSH(env, map[string]string{remote: keys[remote]}, "", "")
cleanup, err := StartSSH(ctx, env, map[string]string{remote: keys[remote]}, "", "")
return env, cleanup, err
}
}
Expand Down
Loading
Loading