Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8060 fix(daemon): trust the backend's SSL_CERT_DIR CAs when syncing repos (#9312)
IA3861e01173fb428
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 4a59f3d242..fdfe72519e 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -238,6 +238,33 @@ Things to know:- **The CA applies to the whole backend process**, not only the Git providerintegration: every outbound TLS client in the backend that uses the systemtrust store trusts it too.+- **Daemons get the CA for git too.** Daemons clone and fetch workspace+ repositories with the `git` installed on their machine, which never sees the+ backend's `SSL_CERT_DIR`. The backend therefore sends the certificates from+ the directories you added to `SSL_CERT_DIR` (the system directories+ `/etc/ssl/certs` and `/etc/pki/tls/certs` are left out) to every daemon with+ the workspace repositories. The daemon adds them to the trust git already+ has on its machine and records the result in each workspace repository's+ git config, which its own clone and fetch and the git commands agents run in+ their checkouts all read. Nothing needs to be installed on the daemon's+ machine. Things to know about it:+ - The trust git already has is kept. If the daemon's machine sets a general+ `http.sslCAInfo` in its system or global git config, the certificates in+ that file are combined with the backend's; otherwise the system CA bundle+ is. The daemon writes the combination to a file of its own and does not+ change the system trust store or that git config.+ - Narrower settings on the daemon's machine win and are not combined: an+ `http.<url>.sslCAInfo` for a host, an `http.sslCAInfo` set in a+ repository's own config, and `GIT_SSL_CAINFO`.+ - Daemons pick up an added, replaced, or removed CA, and changes to the+ machine's own trust, the next time they refresh the workspace+ repositories, which happens before every checkout; they do not need a+ restart. The backend still does. Checkouts created while a CA was+ present keep working after it is removed.+ - Within those repositories, git trusts the backend's CAs for every host,+ not only the one that needs them.+ - Daemons on Windows do not apply it: Git for Windows verifies certificates+ against the Windows certificate store by default, so add the CA there.- **Only the trust problem is fixed.** An expired certificate, or one that doesnot cover the host name in the URL, is still rejected; fix the certificateitself.diff --git a/apps/docs/content/docs/vcs-integration.fr.mdx b/apps/docs/content/docs/vcs-integration.fr.mdxindex 8401428d0b..72ed4e6c9a 100644--- a/apps/docs/content/docs/vcs-integration.fr.mdx+++ b/apps/docs/content/docs/vcs-integration.fr.mdx@@ -61,7 +61,7 @@ Le secret du webhook n'est affiché qu'une seule fois. Copiez-le avant de quitte### Instance avec une autorité de certification privée-Si **Connecter** indique que le certificat du fournisseur « is signed by a certificate authority this server does not trust », le certificat HTTPS de l'instance est émis par une autorité de certification (CA) interne, ou auto-signé, à laquelle le serveur Multica ne fait pas confiance. Un administrateur du serveur doit ajouter cette CA au magasin de confiance du backend : avec Helm, définissez `backend.extraCACerts.configMap` ; avec Docker Compose, montez la CA et définissez `SSL_CERT_DIR`. Les étapes sont décrites dans [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional).+Si **Connecter** indique que le certificat du fournisseur « is signed by a certificate authority this server does not trust », le certificat HTTPS de l'instance est émis par une autorité de certification (CA) interne, ou auto-signé, à laquelle le serveur Multica ne fait pas confiance. Un administrateur du serveur doit ajouter cette CA au magasin de confiance du backend : avec Helm, définissez `backend.extraCACerts.configMap` ; avec Docker Compose, montez la CA et définissez `SSL_CERT_DIR`. Les étapes sont décrites dans [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional). Le backend transmet aussi cette CA aux daemons, afin que leur git puisse cloner les dépôts de la même instance.Multica ne propose pas d'option pour ignorer la vérification du certificat, car la requête de connexion transporte votre jeton d'accès. Si le message indique que le certificat ne correspond pas au nom d'hôte, ou que sa vérification a échoué (par exemple, il a expiré), corrigez le certificat lui-même ; faire confiance à la CA n'y changera rien.diff --git a/apps/docs/content/docs/vcs-integration.ja.mdx b/apps/docs/content/docs/vcs-integration.ja.mdxindex c9ffbe4a68..e4dfd3d729 100644--- a/apps/docs/content/docs/vcs-integration.ja.mdx+++ b/apps/docs/content/docs/vcs-integration.ja.mdx@@ -56,7 +56,7 @@ Webhook secret は一度しか表示されません。ページを離れる前### プライベート CA を使うインスタンス-**接続**で、プロバイダーの証明書が "is signed by a certificate authority this server does not trust" と表示された場合、インスタンスの HTTPS 証明書は Multica サーバーが信頼していない社内 CA で発行されている(または自己署名である)ということです。サーバー管理者がその CA をバックエンドの信頼ストアに追加してください。Helm では `backend.extraCACerts.configMap` を設定し、Docker Compose では CA をマウントして `SSL_CERT_DIR` を設定します。手順は [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional) を参照してください。+**接続**で、プロバイダーの証明書が "is signed by a certificate authority this server does not trust" と表示された場合、インスタンスの HTTPS 証明書は Multica サーバーが信頼していない社内 CA で発行されている(または自己署名である)ということです。サーバー管理者がその CA をバックエンドの信頼ストアに追加してください。Helm では `backend.extraCACerts.configMap` を設定し、Docker Compose では CA をマウントして `SSL_CERT_DIR` を設定します。手順は [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional) を参照してください。バックエンドはこの CA をデーモンにも渡すため、デーモンの git も同じインスタンスのリポジトリをクローンできます。接続リクエストにはアクセストークンが含まれるため、Multica には証明書の検証をスキップするオプションはありません。証明書がホスト名と一致しない、または検証に失敗した(例: 有効期限切れ)と表示された場合は、証明書そのものを修正してください。CA を信頼しても解決しません。diff --git a/apps/docs/content/docs/vcs-integration.ko.mdx b/apps/docs/content/docs/vcs-integration.ko.mdxindex 997533c811..462049e9c8 100644--- a/apps/docs/content/docs/vcs-integration.ko.mdx+++ b/apps/docs/content/docs/vcs-integration.ko.mdx@@ -56,7 +56,7 @@ Webhook secret은 한 번만 표시됩니다. 페이지를 떠나기 전에 복### 사설 CA를 사용하는 인스턴스-**연결** 시 제공자 인증서에 대해 "is signed by a certificate authority this server does not trust"라는 메시지가 나오면, 인스턴스의 HTTPS 인증서가 Multica 서버가 신뢰하지 않는 내부 CA로 발급되었거나 자체 서명된 것입니다. 서버 관리자가 해당 CA를 백엔드 신뢰 저장소에 추가해야 합니다. Helm에서는 `backend.extraCACerts.configMap`을 설정하고, Docker Compose에서는 CA를 마운트한 뒤 `SSL_CERT_DIR`을 설정합니다. 자세한 절차는 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)를 참고하세요.+**연결** 시 제공자 인증서에 대해 "is signed by a certificate authority this server does not trust"라는 메시지가 나오면, 인스턴스의 HTTPS 인증서가 Multica 서버가 신뢰하지 않는 내부 CA로 발급되었거나 자체 서명된 것입니다. 서버 관리자가 해당 CA를 백엔드 신뢰 저장소에 추가해야 합니다. Helm에서는 `backend.extraCACerts.configMap`을 설정하고, Docker Compose에서는 CA를 마운트한 뒤 `SSL_CERT_DIR`을 설정합니다. 자세한 절차는 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)를 참고하세요. 백엔드는 이 CA를 데몬에도 전달하므로, 데몬의 git도 같은 인스턴스의 저장소를 클론할 수 있습니다.연결 요청에는 액세스 token이 포함되므로 Multica는 인증서 검증을 건너뛰는 옵션을 제공하지 않습니다. 인증서가 호스트 이름과 일치하지 않거나 검증에 실패했다는(예: 만료) 메시지가 나오면 인증서 자체를 고쳐야 합니다. CA를 신뢰하는 것으로는 해결되지 않습니다.diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdxindex b17abb09b8..5635d75c4d 100644--- a/apps/docs/content/docs/vcs-integration.mdx+++ b/apps/docs/content/docs/vcs-integration.mdx@@ -61,7 +61,7 @@ The webhook secret is shown only once. Copy it before leaving the page. Reconnec### Instance with a private CA-If **Connect** reports that the provider's certificate "is signed by a certificate authority this server does not trust", the instance's HTTPS certificate comes from an internal CA (or is self-signed) that the Multica server does not trust. A server operator adds that CA to the backend's trust store: with Helm, set `backend.extraCACerts.configMap`; with Docker Compose, mount the CA and set `SSL_CERT_DIR`. See [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional) for the steps.+If **Connect** reports that the provider's certificate "is signed by a certificate authority this server does not trust", the instance's HTTPS certificate comes from an internal CA (or is self-signed) that the Multica server does not trust. A server operator adds that CA to the backend's trust store: with Helm, set `backend.extraCACerts.configMap`; with Docker Compose, mount the CA and set `SSL_CERT_DIR`. See [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional) for the steps. The backend also passes that CA to daemons, so their git can clone repositories from the same instance.Multica has no option to skip certificate verification, because the connect request carries your access token. If the message says the certificate does not match the host name, or failed verification (for example, it has expired), fix the certificate itself; trusting the CA does not help.diff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdxindex 4990e07945..3c01e8e04e 100644--- a/apps/docs/content/docs/vcs-integration.zh.mdx+++ b/apps/docs/content/docs/vcs-integration.zh.mdx@@ -56,7 +56,7 @@ Webhook 密钥只显示一次,请在离开页面前复制。重新连接同一### 实例使用私有 CA-如果点击 **连接** 后提示提供方的证书 "is signed by a certificate authority this server does not trust",说明实例的 HTTPS 证书由内部 CA 签发(或是自签名证书),而 Multica 服务端不信任这个 CA。需要由服务端管理员把该 CA 加入后端的信任库:使用 Helm 时设置 `backend.extraCACerts.configMap`;使用 Docker Compose 时挂载 CA 并设置 `SSL_CERT_DIR`。具体步骤见 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)。+如果点击 **连接** 后提示提供方的证书 "is signed by a certificate authority this server does not trust",说明实例的 HTTPS 证书由内部 CA 签发(或是自签名证书),而 Multica 服务端不信任这个 CA。需要由服务端管理员把该 CA 加入后端的信任库:使用 Helm 时设置 `backend.extraCACerts.configMap`;使用 Docker Compose 时挂载 CA 并设置 `SSL_CERT_DIR`。具体步骤见 [Private CA certificates](https://github.com/multica-ai/multica/blob/main/SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional)。后端还会把该 CA 下发给守护进程,使守护进程的 git 也能克隆同一实例上的仓库。Multica 不提供跳过证书校验的选项,因为连接请求会携带你的访问令牌。如果提示证书与主机名不匹配,或证书校验失败(例如已过期),需要修复证书本身,信任 CA 解决不了。diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex 1ef312a814..4043489dab 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -113,9 +113,11 @@ backend:# configMap to an existing ConfigMap in the release namespace whose keys are# PEM certificate files. The chart mounts it read-only and adds it to the# system trust store via SSL_CERT_DIR: public CAs stay trusted and TLS- # verification stays on. The backend reads the certificates at startup;- # `helm upgrade` rolls it when the ConfigMap changed, otherwise run- # `kubectl rollout restart` after updating it.+ # verification stays on. The backend also sends these certificates to+ # daemons, whose git then trusts them for repositories on the same hosts.+ # The backend reads the certificates at startup; `helm upgrade` rolls it+ # when the ConfigMap changed, otherwise run `kubectl rollout restart` after+ # updating it.extraCACerts:configMap: ""# All non-secret backend env. Secret values come from `existingSecret`.diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e11dfe4b9b..b878cce6f8 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -27,6 +27,7 @@ import ("github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/gitca""github.com/multica-ai/multica/server/internal/handler""github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/integrations/channel/engine"@@ -446,6 +447,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusLLMMaxRetries: opts.LLMMaxRetries,LLMDisableThinking: opts.LLMDisableThinking,ServerVersion: normalizeServerVersion(version),+ GitExtraCACerts: gitca.Load(slog.Default()),}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)invitationRateLimits := handler.DefaultInvitationRateLimits()diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 46959da1ac..3095522259 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -1078,6 +1078,7 @@ type RegisterResponse struct {Repos []RepoData `json:"repos"`ReposVersion string `json:"repos_version"`Settings json.RawMessage `json:"settings,omitempty"`+ CACerts string `json:"ca_certs,omitempty"`}func (c *Client) Register(ctx context.Context, req map[string]any) (*RegisterResponse, error) {@@ -1093,6 +1094,9 @@ type WorkspaceReposResponse struct {Repos []RepoData `json:"repos"`ReposVersion string `json:"repos_version"`Settings json.RawMessage `json:"settings,omitempty"`+ // CACerts is the server's extra CA certificates (PEM) for git; see+ // applyGitCACerts.+ CACerts string `json:"ca_certs,omitempty"`}func (c *Client) GetWorkspaceRepos(ctx context.Context, workspaceID string) (*WorkspaceReposResponse, error) {diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 3fcb1220c2..fdbc922a9e 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -359,7 +359,6 @@ type workspaceState struct {taskRepoURLs map[string]struct{}taskRepoRefs map[string]map[string]string // taskID -> repo URL -> checkout refsettings json.RawMessage // workspace settings (JSONB)- lastRepoSyncErr stringrepoRefreshMu contextLock// coAuthorPublishMu serializes publication of the Co-authored-by verdict// for this workspace. Unlike the fields above it is NOT guarded by@@ -438,6 +437,10 @@ type Daemon struct {skillCache *SkillBundleCachelogger *slog.Logger+ // gitCALastErr is the last applyGitCACerts failure, so a persistent one+ // (e.g. on Windows) is logged once rather than on every repo refresh.+ gitCALastErr atomic.Pointer[string]+// terminalReports is the durable outbox for complete/fail callbacks. The// sender hook is production-wired through Client and overridable in focused// tests; terminalReportWakeup coalesces new-report and reconnect nudges.@@ -3197,14 +3200,6 @@ func repoAllowlist(repos []RepoData) map[string]struct{} {return allowed}-func (d *Daemon) setWorkspaceRepoSyncError(workspaceID, syncErr string) {- d.mu.Lock()- defer d.mu.Unlock()- if ws, ok := d.workspaces[workspaceID]; ok {- ws.lastRepoSyncErr = syncErr- }-}-func (d *Daemon) workspaceRepoAllowed(workspaceID, repoURL string) bool {d.mu.Lock()defer d.mu.Unlock()@@ -3260,16 +3255,6 @@ func (d *Daemon) repoBarePathIsLive(barePath string) bool {return false}-func (d *Daemon) workspaceLastRepoSyncErr(workspaceID string) string {- d.mu.Lock()- defer d.mu.Unlock()- ws, ok := d.workspaces[workspaceID]- if !ok {- return ""- }- return ws.lastRepoSyncErr-}-// workspaceCoAuthoredByEnabled returns whether the Co-authored-by hook should// be installed for the given workspace. Defaults to true when either setting// is absent (new workspaces, older servers that don't send settings).@@ -3415,12 +3400,16 @@ func (d *Daemon) waitBackgroundSyncs() {}func (d *Daemon) syncWorkspaceRepos(workspaceID string, repos []RepoData) {- d.syncWorkspaceReposContext(context.Background(), workspaceID, repos)+ _ = d.syncWorkspaceReposContext(context.Background(), workspaceID, repos)}-func (d *Daemon) syncWorkspaceReposContext(ctx context.Context, workspaceID string, repos []RepoData) {+// syncWorkspaceReposContext returns the sync error to its caller rather than+// recording it per workspace: background syncs of other repos run+// concurrently, and a shared slot let a later successful sync erase the+// failure before a checkout could report it.+func (d *Daemon) syncWorkspaceReposContext(ctx context.Context, workspaceID string, repos []RepoData) error {if d.repoCache == nil {- return+ return nil}var err errorif cache, ok := d.repoCache.(interface {@@ -3431,11 +3420,9 @@ func (d *Daemon) syncWorkspaceReposContext(ctx context.Context, workspaceID strierr = d.repoCache.Sync(workspaceID, repoDataToInfo(repos))}if err != nil {- d.setWorkspaceRepoSyncError(workspaceID, err.Error())d.logger.Warn("repo cache sync failed", "workspace_id", workspaceID, "error", err)- return}- d.setWorkspaceRepoSyncError(workspaceID, "")+ return err}func (d *Daemon) refreshWorkspaceRepos(ctx context.Context, workspaceID string) (*WorkspaceReposResponse, error) {@@ -3446,6 +3433,7 @@ func (d *Daemon) refreshWorkspaceRepos(ctx context.Context, workspaceID string)if err != nil {return nil, err}+ d.applyGitCACerts(resp.CACerts)d.mu.Lock()if ws, ok := d.workspaces[workspaceID]; ok {@@ -3933,7 +3921,7 @@ func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL strinreturn nil}- d.syncWorkspaceReposContext(ctx, workspaceID, resp.Repos)+ syncErr := d.syncWorkspaceReposContext(ctx, workspaceID, resp.Repos)if err := ctx.Err(); err != nil {return context.Cause(ctx)}@@ -3942,8 +3930,8 @@ func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL strinreturn nil}- if syncErr := d.workspaceLastRepoSyncErr(workspaceID); syncErr != "" {- return fmt.Errorf("repo is configured but not synced: %s", syncErr)+ if syncErr != nil {+ return fmt.Errorf("repo is configured but not synced: %w", syncErr)}return fmt.Errorf("repo is configured but not synced")@@ -4326,6 +4314,7 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bocontinue}+ d.applyGitCACerts(resp.CACerts)if d.repoCache != nil && len(resp.Repos) > 0 {go d.syncWorkspaceRepos(id, resp.Repos)}diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 649631f7c4..9999d04983 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -5053,11 +5053,70 @@ func TestEnsureRepoReadyReportsSyncFailure(t *testing.T) {d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)err := d.ensureRepoReady(context.Background(), "ws-1", missingRepo)- if err == nil || !strings.Contains(err.Error(), "repo is configured but not synced:") {- t.Fatalf("expected sync failure error, got %v", err)+ if err == nil || !strings.Contains(err.Error(), "repo is configured but not synced: git clone --bare:") {+ t.Fatalf("expected sync failure error with git's output, got %v", err)+ }+}++// syncRaceRepoCache fails the sync of failURL and, on the Lookup that+// follows, runs a successful background sync of another repo: the window in+// which a shared per-workspace error slot used to be cleared.+type syncRaceRepoCache struct {+ d *Daemon+ failURL string+ mu sync.Mutex+ failedOnce bool+ raced bool+}++func (c *syncRaceRepoCache) Lookup(string, string) string {+ c.mu.Lock()+ race := c.failedOnce && !c.raced+ c.raced = c.raced || race+ c.mu.Unlock()+ if race {+ c.d.syncWorkspaceRepos("ws-1", []RepoData{{URL: "https://example.com/other.git"}})+ }+ return ""+}+func (c *syncRaceRepoCache) BarePath(string, string) string { return "" }+func (c *syncRaceRepoCache) Sync(_ string, repos []repocache.RepoInfo) error {+ for _, r := range repos {+ if r.URL == c.failURL {+ c.mu.Lock()+ c.failedOnce = true+ c.mu.Unlock()+ return errors.New("git clone --bare: server certificate verification failed")+ }+ }+ return nil+}+func (c *syncRaceRepoCache) WithRepoLock(_ string, fn func() error) error { return fn() }+func (c *syncRaceRepoCache) CreateWorktree(repocache.WorktreeParams) (*repocache.WorktreeResult, error) {+ return nil, nil+}++func TestEnsureRepoReadyKeepsSyncFailureDespiteConcurrentSuccess(t *testing.T) {+ t.Parallel()++ const repoURL = "https://devops.example.com/team/_git/app"+ d := newRepoReadyTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: "ws-1",+ Repos: []RepoData{{URL: repoURL}},+ ReposVersion: "v1",+ })+ })+ cache := &syncRaceRepoCache{d: d, failURL: repoURL}+ d.repoCache = cache+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)++ err := d.ensureRepoReady(context.Background(), "ws-1", repoURL)+ if !cache.raced {+ t.Fatal("test did not exercise the concurrent sync")}- if got := d.workspaceLastRepoSyncErr("ws-1"); got == "" {- t.Fatal("expected lastRepoSyncErr to be recorded")+ if err == nil || !strings.Contains(err.Error(), "server certificate verification failed") {+ t.Fatalf("expected the checkout's own sync failure, got %v", err)}}diff --git a/server/internal/daemon/git_ca.go b/server/internal/daemon/git_ca.gonew file mode 100644index 0000000000..00ceebacf6--- /dev/null+++ b/server/internal/daemon/git_ca.go@@ -0,0 +1,27 @@+package daemon++// gitCACertSetter is implemented by repocache.Cache. It is optional so test+// doubles of repoCacheBackend do not have to implement it.+type gitCACertSetter interface {+ SetExtraCACerts(pemCerts string) error+}++// applyGitCACerts hands the server's extra CA certificates to the repo cache,+// which makes git trust them for clone, fetch, and agents' push. It runs on+// registration and on every workspace repo refresh (which precedes each+// checkout), so a CA rotated on the server reaches the daemon without a+// restart. An empty value removes a previously applied bundle.+func (d *Daemon) applyGitCACerts(pemCerts string) {+ cache, ok := d.repoCache.(gitCACertSetter)+ if !ok {+ return+ }+ err := cache.SetExtraCACerts(pemCerts)+ msg := ""+ if err != nil {+ msg = err.Error()+ }+ if prev := d.gitCALastErr.Swap(&msg); err != nil && (prev == nil || *prev != msg) {+ d.logger.Warn("git CA: could not apply server CA certificates; repositories on hosts with a private CA may fail to sync", "error", err)+ }+}diff --git a/server/internal/daemon/git_ca_test.go b/server/internal/daemon/git_ca_test.gonew file mode 100644index 0000000000..92fef95db1--- /dev/null+++ b/server/internal/daemon/git_ca_test.go@@ -0,0 +1,83 @@+package daemon++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/daemon/repocache"+)++type caRecordingCache struct {+ mu sync.Mutex+ certs []string+ err error+}++func (c *caRecordingCache) Lookup(string, string) string { return "" }+func (c *caRecordingCache) BarePath(string, string) string { return "" }+func (c *caRecordingCache) Sync(string, []repocache.RepoInfo) error { return nil }+func (c *caRecordingCache) WithRepoLock(_ string, fn func() error) error { return fn() }+func (c *caRecordingCache) CreateWorktree(repocache.WorktreeParams) (*repocache.WorktreeResult, error) {+ return nil, nil+}++func (c *caRecordingCache) SetExtraCACerts(pemCerts string) error {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.certs = append(c.certs, pemCerts)+ return c.err+}++func TestRefreshWorkspaceReposAppliesServerCACerts(t *testing.T) {+ t.Parallel()++ const pemCerts = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ json.NewEncoder(w).Encode(WorkspaceReposResponse{WorkspaceID: "ws-1", ReposVersion: "v1", CACerts: pemCerts})+ }))+ t.Cleanup(srv.Close)++ cache := &caRecordingCache{}+ d := &Daemon{+ client: NewClient(srv.URL),+ repoCache: cache,+ logger: slog.Default(),+ workspaces: map[string]*workspaceState{"ws-1": newWorkspaceState("ws-1", nil, "", nil, nil)},+ }+ if _, err := d.refreshWorkspaceRepos(context.Background(), "ws-1"); err != nil {+ t.Fatal(err)+ }+ if len(cache.certs) != 1 || cache.certs[0] != pemCerts {+ t.Fatalf("SetExtraCACerts calls = %q, want the server's PEM once", cache.certs)+ }+}++func TestApplyGitCACertsLogsPersistentFailureOnce(t *testing.T) {+ t.Parallel()++ var logs bytes.Buffer+ cache := &caRecordingCache{err: errors.New("not applied on Windows")}+ d := &Daemon{repoCache: cache, logger: slog.New(slog.NewTextHandler(&logs, nil))}++ d.applyGitCACerts("pem")+ d.applyGitCACerts("pem")+ if n := strings.Count(logs.String(), "git CA:"); n != 1 {+ t.Fatalf("logged %d warnings, want 1:\n%s", n, logs.String())+ }++ cache.err = nil+ d.applyGitCACerts("pem")+ cache.err = errors.New("not applied on Windows")+ d.applyGitCACerts("pem")+ if n := strings.Count(logs.String(), "git CA:"); n != 2 {+ t.Fatalf("logged %d warnings after recovery and new failure, want 2", n)+ }+}diff --git a/server/internal/daemon/repocache/ca.go b/server/internal/daemon/repocache/ca.gonew file mode 100644index 0000000000..e4db6e99e3--- /dev/null+++ b/server/internal/daemon/repocache/ca.go@@ -0,0 +1,253 @@+package repocache++import (+ "bytes"+ "context"+ "crypto/x509"+ "encoding/pem"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync/atomic"+ "time"+)++// caBundleConfigKey is the git setting that points at the CA bundle.+const caBundleConfigKey = "http.sslCAInfo"++// caBundleState describes the bundle file this daemon manages. It is package+// state because the isolated-checkout helpers that must record it are+// package-level functions.+type caBundleState struct {+ path string+ // active is set while the server sends extra CAs: repositories should+ // point at path. Once cleared, path still holds the machine's own trust+ // so checkouts that point at it keep working until they are reconfigured.+ active bool+}++var caState atomic.Pointer[caBundleState]++// activeCABundle returns the bundle path git must use, or "" when the server+// sent no extra CAs.+func activeCABundle() string {+ if st := caState.Load(); st != nil && st.active {+ return st.path+ }+ return ""+}++// systemCABundleFiles mirrors crypto/x509's certFiles on Linux plus the+// macOS/BSD location: the bundle libcurl uses by default on these systems.+var systemCABundleFiles = []string{+ "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.+ "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL 6+ "/etc/ssl/ca-bundle.pem", // OpenSUSE+ "/etc/pki/tls/cacert.pem", // OpenELEC+ "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // CentOS/RHEL 7+ "/etc/ssl/cert.pem", // Alpine Linux, macOS+}++func (c *Cache) caBundlePath() string {+ return filepath.Join(c.root, ".ca", "bundle.pem")+}++// SetExtraCACerts makes git trust pemCerts on top of the trust it already has+// on this machine.+//+// git accepts a CA only as a file, and http.sslCAInfo replaces its default+// trust, so the bundle is the machine's trust (see machineCATrust) followed by+// pemCerts. Repositories point at it through their own config, which a+// repository-local value set by hand, a URL-scoped http.<url>.sslCAInfo, and+// GIT_SSL_CAINFO all override.+//+// An empty pemCerts deactivates the bundle without deleting it: checkouts+// created while it was active still point at the file, so it is rewritten to+// the machine's trust alone and each repository drops the reference the next+// time this cache configures it.+func (c *Cache) SetExtraCACerts(pemCerts string) error {+ c.caMu.Lock()+ defer c.caMu.Unlock()++ path := c.caBundlePath()+ extra, err := normalizeCACerts(pemCerts)+ if err != nil {+ return err+ }++ if len(extra) == 0 {+ caState.Store(&caBundleState{path: path})+ if _, err := os.Stat(path); err != nil {+ return nil+ }+ base, err := machineCATrust(path)+ if err != nil {+ // Keep the previous bundle: stale trust beats a missing file.+ return fmt.Errorf("refresh CA bundle after removal: %w", err)+ }+ return writeBundleIfChanged(path, base, nil)+ }++ if runtime.GOOS == "windows" {+ // Git for Windows defaults to Schannel, which ignores sslCAInfo, and+ // its OpenSSL backend ships its own bundle we would have to locate.+ return errors.New("private CA certificates from the server are not applied on Windows; add them to the Windows certificate store")+ }+ base, err := machineCATrust(path)+ if err != nil {+ return err+ }+ if err := writeBundleIfChanged(path, base, extra); err != nil {+ return err+ }+ caState.Store(&caBundleState{path: path, active: true})+ return nil+}++// machineCATrust returns the CA certificates git on this machine trusts for a+// host without a URL-scoped setting: the file named by a general+// http.sslCAInfo in the system or global config (or GIT_CONFIG_* env), so an+// operator's own internal CAs stay trusted, or else the system bundle.+// ownPath is skipped so the bundle never feeds on itself.+func machineCATrust(ownPath string) ([]byte, error) {+ out, err := runGitOutputWithTimeout(gitConfigReadTimeout, "config", "--type=path", "--get", caBundleConfigKey)+ if configured := strings.TrimSpace(string(out)); err == nil && configured != "" && filepath.Clean(configured) != filepath.Clean(ownPath) {+ data, err := os.ReadFile(configured)+ if err != nil {+ return nil, fmt.Errorf("read %s from git config: %w", caBundleConfigKey, err)+ }+ return data, nil+ }+ if system := readSystemCABundle(); len(system) > 0 {+ return system, nil+ }+ return nil, errors.New("no system CA bundle found; not overriding git's trust store")+}++const gitConfigReadTimeout = 30 * time.Second++func writeBundleIfChanged(path string, base, extra []byte) error {+ var bundle bytes.Buffer+ bundle.Write(base)+ if len(extra) > 0 {+ if !bytes.HasSuffix(base, []byte("\n")) {+ bundle.WriteByte('\n')+ }+ bundle.Write(extra)+ }+ if current, err := os.ReadFile(path); err == nil && bytes.Equal(current, bundle.Bytes()) {+ return nil+ }+ if err := writeFileAtomic(path, bundle.Bytes()); err != nil {+ return fmt.Errorf("write CA bundle: %w", err)+ }+ return nil+}++// normalizeCACerts keeps the parseable CERTIFICATE blocks of raw. An input+// with content but no usable certificate is an error so a broken server value+// does not silently drop a bundle that was working.+func normalizeCACerts(raw string) ([]byte, error) {+ if strings.TrimSpace(raw) == "" {+ return nil, nil+ }+ data := []byte(raw)+ var out bytes.Buffer+ for len(data) > 0 {+ var block *pem.Block+ block, data = pem.Decode(data)+ if block == nil {+ break+ }+ if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {+ continue+ }+ if _, err := x509.ParseCertificate(block.Bytes); err != nil {+ continue+ }+ _ = pem.Encode(&out, block)+ }+ if out.Len() == 0 {+ return nil, errors.New("server sent CA certificates without a valid PEM certificate")+ }+ return out.Bytes(), nil+}++func readSystemCABundle() []byte {+ files := systemCABundleFiles+ if f := os.Getenv("SSL_CERT_FILE"); f != "" {+ files = append([]string{f}, files...)+ }+ for _, f := range files {+ if data, err := os.ReadFile(f); err == nil && len(bytes.TrimSpace(data)) > 0 {+ return data+ }+ }+ return nil+}++func writeFileAtomic(path string, data []byte) error {+ dir := filepath.Dir(path)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return err+ }+ tmp, err := os.CreateTemp(dir, ".bundle-*.pem")+ if err != nil {+ return err+ }+ defer os.Remove(tmp.Name())+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ return os.Rename(tmp.Name(), path)+}++// caCloneArgs returns the git options a clone needs to trust the bundle.+// The new repository has no config yet; configureRepoCABundleContext records+// the setting right after the clone.+func caCloneArgs() []string {+ if bundle := activeCABundle(); bundle != "" {+ return []string{"-c", caBundleConfigKey + "=" + bundle}+ }+ return nil+}++// configureRepoCABundleLogged is configureRepoCABundleContext for paths where+// a failure must not block the clone, fetch, or checkout around it.+func (c *Cache) configureRepoCABundleLogged(ctx context.Context, repoPath string) {+ if err := configureRepoCABundleContext(ctx, repoPath); err != nil {+ c.logger.Warn("repo cache: could not record CA bundle in repo config", "path", repoPath, "error", err)+ }+}++// configureRepoCABundleContext points a repository's own config at the bundle+// while it is active and removes that reference once it is not. The daemon's+// fetches in the bare cache, agents' git in linked worktrees (which share the+// cache's config), and isolated checkouts all read it from there. A value+// that is not this cache's bundle was set by someone else and is left alone.+func configureRepoCABundleContext(ctx context.Context, repoPath string) error {+ st := caState.Load()+ if st == nil {+ return nil+ }+ out, _ := runGitOutputContext(ctx, "-C", repoPath, "config", "--local", "--get", caBundleConfigKey)+ have := strings.TrimSpace(string(out))+ switch {+ case st.active && have == "":+ if out, err := runGitCombinedOutputContext(ctx, "-C", repoPath, "config", "--local", caBundleConfigKey, st.path); err != nil {+ return fmt.Errorf("set %s: %s: %w", caBundleConfigKey, strings.TrimSpace(string(out)), err)+ }+ case !st.active && have == st.path:+ if out, err := runGitCombinedOutputContext(ctx, "-C", repoPath, "config", "--local", "--unset", caBundleConfigKey); err != nil {+ return fmt.Errorf("unset %s: %s: %w", caBundleConfigKey, strings.TrimSpace(string(out)), err)+ }+ }+ return nil+}diff --git a/server/internal/daemon/repocache/ca_test.go b/server/internal/daemon/repocache/ca_test.gonew file mode 100644index 0000000000..913d73b48e--- /dev/null+++ b/server/internal/daemon/repocache/ca_test.go@@ -0,0 +1,297 @@+package repocache++import (+ "context"+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/tls"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "io"+ "log/slog"+ "math/big"+ "net"+ "net/http/cgi"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++// isolateGitConfig keeps the developer's own git config out of a test and+// resets the package CA state afterwards. Tests using it cannot run in+// parallel because they set environment variables.+func isolateGitConfig(t *testing.T) string {+ t.Helper()+ global := filepath.Join(t.TempDir(), "gitconfig")+ if err := os.WriteFile(global, nil, 0o644); err != nil {+ t.Fatal(err)+ }+ t.Setenv("GIT_CONFIG_GLOBAL", global)+ t.Setenv("GIT_CONFIG_NOSYSTEM", "1")+ t.Setenv("NO_PROXY", "*")+ t.Setenv("no_proxy", "*")+ t.Cleanup(func() { caState.Store(nil) })+ return global+}++// newServerCert returns a self-signed certificate for 127.0.0.1 and its PEM.+func newServerCert(t *testing.T, name string) (tls.Certificate, string) {+ t.Helper()+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ tmpl := &x509.Certificate{+ SerialNumber: big.NewInt(time.Now().UnixNano()),+ Subject: pkix.Name{CommonName: name},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().Add(time.Hour),+ IsCA: true,+ BasicConstraintsValid: true,+ KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},+ IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ if err != nil {+ t.Fatal(err)+ }+ return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key},+ string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))+}++// newHTTPSGitServer serves a one-commit repository over HTTPS, with its own+// self-signed certificate, through git http-backend. It returns the clone URL+// and the certificate as PEM.+func newHTTPSGitServer(t *testing.T, name string) (string, string) {+ t.Helper()+ if runtime.GOOS == "windows" {+ t.Skip("private CA bundles are not applied on Windows")+ }+ gitPath, err := exec.LookPath("git")+ if err != nil {+ t.Skip("git not available")+ }+ execPath, err := exec.Command(gitPath, "--exec-path").Output()+ if err != nil {+ t.Skip("git --exec-path failed")+ }+ backend := filepath.Join(strings.TrimSpace(string(execPath)), "git-http-backend")+ if _, err := os.Stat(backend); err != nil {+ t.Skip("git-http-backend not available")+ }+ if len(readSystemCABundle()) == 0 {+ t.Skip("no system CA bundle")+ }++ root := t.TempDir()+ served := filepath.Join(root, "app.git")+ if out, err := exec.Command(gitPath, "clone", "--bare", createTestRepo(t), served).CombinedOutput(); err != nil {+ t.Fatalf("prepare served repo: %s: %v", out, err)+ }+ // http-backend refuses anonymous pushes unless receive-pack is enabled.+ if out, err := exec.Command(gitPath, "-C", served, "config", "http.receivepack", "true").CombinedOutput(); err != nil {+ t.Fatalf("enable receive-pack: %s: %v", out, err)+ }++ cert, certPEM := newServerCert(t, name)+ srv := httptest.NewUnstartedServer(&cgi.Handler{+ Path: backend,+ Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"},+ })+ srv.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}+ srv.StartTLS()+ t.Cleanup(srv.Close)+ return srv.URL + "/app.git", certPEM+}++// agentGit runs git the way an agent does: with the inherited environment and+// no daemon-added options, so only git config can supply the CA bundle.+func agentGit(t *testing.T, dir string, args ...string) (string, error) {+ t.Helper()+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)+ cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")+ out, err := cmd.CombinedOutput()+ return string(out), err+}++func newTestCacheQuiet(t *testing.T) *Cache {+ t.Helper()+ return New(t.TempDir(), slog.New(slog.NewTextHandler(io.Discard, nil)))+}++func createCheckouts(t *testing.T, cache *Cache, repoURL, taskID string) map[string]string {+ t.Helper()+ paths := map[string]string{}+ for name, isolated := range map[string]bool{"linked": false, "isolated": true} {+ result, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: "ws-1",+ RepoURL: repoURL,+ WorkDir: t.TempDir(),+ AgentName: "agent",+ TaskID: taskID,+ IsolatedGitMetadata: isolated,+ })+ if err != nil {+ t.Fatalf("CreateWorktree(%s): %v", name, err)+ }+ paths[name] = result.Path+ }+ return paths+}++func TestExtraCACertsLetGitReachPrivateCAHost(t *testing.T) {+ isolateGitConfig(t)+ repoURL, caPEM := newHTTPSGitServer(t, "backend-ca")+ cache := newTestCacheQuiet(t)+ repos := []RepoInfo{{URL: repoURL}}++ err := cache.Sync("ws-1", repos)+ if err == nil || !strings.Contains(strings.ToLower(err.Error()), "certificate") {+ t.Fatalf("sync without the CA: want a certificate error, got %v", err)+ }++ if err := cache.SetExtraCACerts(caPEM); err != nil {+ t.Fatalf("SetExtraCACerts: %v", err)+ }+ if err := cache.Sync("ws-1", repos); err != nil {+ t.Fatalf("sync with the CA: %v", err)+ }+ bundle, err := os.ReadFile(cache.caBundlePath())+ if err != nil {+ t.Fatalf("read bundle: %v", err)+ }+ if string(bundle) != string(readSystemCABundle())+caPEM && string(bundle) != string(readSystemCABundle())+"\n"+caPEM {+ t.Fatal("bundle must be the system bundle followed by the server's CA")+ }++ for name, path := range createCheckouts(t, cache, repoURL, "task-ca") {+ if out, err := agentGit(t, path, "fetch", "origin"); err != nil {+ t.Fatalf("agent fetch (%s): %s: %v", name, out, err)+ }+ if out, err := agentGit(t, path, "push", "origin", "HEAD:refs/heads/push-"+name); err != nil {+ t.Fatalf("agent push (%s): %s: %v", name, out, err)+ }+ }++ if err := cache.SetExtraCACerts(""); err != nil {+ t.Fatalf("clear CA: %v", err)+ }+ if got, err := os.ReadFile(cache.caBundlePath()); err != nil || string(got) != string(readSystemCABundle()) {+ t.Fatalf("after clearing, the bundle must hold the system trust alone (err=%v)", err)+ }+ barePath := cache.Lookup("ws-1", repoURL)+ if err := configureRepoCABundleContext(context.Background(), barePath); err != nil {+ t.Fatal(err)+ }+ if out, _ := agentGit(t, barePath, "config", "--local", "--get", caBundleConfigKey); strings.TrimSpace(out) != "" {+ t.Fatalf("%s still set after clearing: %q", caBundleConfigKey, out)+ }+}++// An operator's general http.sslCAInfo must keep working while backend CAs+// are added, and checkouts created meanwhile must keep working after the+// backend CAs are removed.+func TestExtraCACertsKeepOperatorTrust(t *testing.T) {+ global := isolateGitConfig(t)+ operatorURL, operatorPEM := newHTTPSGitServer(t, "operator-ca")+ backendURL, backendPEM := newHTTPSGitServer(t, "backend-ca")++ machinePEM := filepath.Join(t.TempDir(), "machine.pem")+ machineTrust := string(readSystemCABundle()) + "\n" + operatorPEM+ if err := os.WriteFile(machinePEM, []byte(machineTrust), 0o644); err != nil {+ t.Fatal(err)+ }+ if out, err := exec.Command("git", "config", "--file", global, caBundleConfigKey, machinePEM).CombinedOutput(); err != nil {+ t.Fatalf("set operator %s: %s: %v", caBundleConfigKey, out, err)+ }++ cache := newTestCacheQuiet(t)+ if err := cache.Sync("ws-1", []RepoInfo{{URL: operatorURL}}); err != nil {+ t.Fatalf("operator repo before backend CAs: %v", err)+ }++ if err := cache.SetExtraCACerts(backendPEM); err != nil {+ t.Fatalf("SetExtraCACerts: %v", err)+ }+ if bundle, _ := os.ReadFile(cache.caBundlePath()); !strings.HasPrefix(string(bundle), machineTrust) {+ t.Fatal("bundle must start with the operator's http.sslCAInfo, not the system bundle")+ }+ if err := cache.Sync("ws-1", []RepoInfo{{URL: operatorURL}, {URL: backendURL}}); err != nil {+ t.Fatalf("sync with backend CAs: %v", err)+ }+ operatorCheckouts := createCheckouts(t, cache, operatorURL, "task-op")+ for name, path := range operatorCheckouts {+ if out, err := agentGit(t, path, "fetch", "origin"); err != nil {+ t.Fatalf("agent fetch from operator repo (%s): %s: %v", name, out, err)+ }+ }+ for name, path := range createCheckouts(t, cache, backendURL, "task-be") {+ if out, err := agentGit(t, path, "fetch", "origin"); err != nil {+ t.Fatalf("agent fetch from backend-CA repo (%s): %s: %v", name, out, err)+ }+ }++ if err := cache.SetExtraCACerts(""); err != nil {+ t.Fatalf("clear CA: %v", err)+ }+ // Existing checkouts still point at the bundle and are not revisited.+ for name, path := range operatorCheckouts {+ if out, err := agentGit(t, path, "fetch", "origin"); err != nil {+ t.Fatalf("agent fetch from operator repo after clearing (%s): %s: %v", name, out, err)+ }+ }+ if got, err := os.ReadFile(cache.caBundlePath()); err != nil || string(got) != machineTrust {+ t.Fatalf("after clearing, the bundle must hold the operator's trust alone (err=%v)", err)+ }+ if err := cache.Sync("ws-1", []RepoInfo{{URL: operatorURL}}); err != nil {+ t.Fatalf("operator repo after clearing: %v", err)+ }+}++func TestConfigureRepoCABundleKeepsManualValue(t *testing.T) {+ isolateGitConfig(t)+ repo := createTestRepo(t)+ const manual = "/etc/custom/ca.pem"+ if out, err := agentGit(t, repo, "config", "--local", caBundleConfigKey, manual); err != nil {+ t.Fatalf("set manual value: %s: %v", out, err)+ }++ for _, active := range []bool{true, false} {+ caState.Store(&caBundleState{path: "/tmp/managed/bundle.pem", active: active})+ if err := configureRepoCABundleContext(context.Background(), repo); err != nil {+ t.Fatal(err)+ }+ if out, _ := agentGit(t, repo, "config", "--local", "--get", caBundleConfigKey); strings.TrimSpace(out) != manual {+ t.Fatalf("active=%v: manual %s was changed to %q", active, caBundleConfigKey, out)+ }+ }+}++func TestSetExtraCACertsRejectsInvalidPEM(t *testing.T) {+ isolateGitConfig(t)+ cache := newTestCacheQuiet(t)+ if err := cache.SetExtraCACerts("not a certificate"); err == nil {+ t.Fatal("expected an error for input without a certificate")+ }+ if activeCABundle() != "" {+ t.Fatal("invalid input must not activate a bundle")+ }+}++func TestGitEnvDoesNotOverrideRepoConfig(t *testing.T) {+ isolateGitConfig(t)+ caState.Store(&caBundleState{path: "/tmp/managed/bundle.pem", active: true})+ for _, kv := range gitEnv() {+ if strings.Contains(kv, caBundleConfigKey) {+ t.Fatalf("gitEnv must not set %s, which would override operator config: %s", caBundleConfigKey, kv)+ }+ }+}diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 3d754246c1..c6ef339e93 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -173,6 +173,7 @@ type Cache struct {// worktree admin dirs) don't tolerate parallel mutations on the same// repo. Separate repos are independent and run concurrently.repoLocks sync.Map // barePath -> *repoLock+ caMu sync.Mutex}// ErrRepoBusy means a foreground checkout could not acquire its repository@@ -379,6 +380,7 @@ func (c *Cache) SyncContext(ctx context.Context, workspaceID string, repos []Repif isBareRepo(barePath) {// Already cached — fetch latest.c.logger.Info("repo cache: fetching", "url", repo.URL, "path", barePath)+ c.configureRepoCABundleLogged(ctx, barePath)if err := gitFetchContext(ctx, barePath); err != nil {c.logger.Warn("repo cache: fetch failed", "url", repo.URL, "error", err)if firstErr == nil {@@ -593,11 +595,17 @@ func gitCloneBare(url, dest string) error {}func gitCloneBareContext(ctx context.Context, url, dest string) error {- if out, err := runGitCombinedOutputContext(ctx, "clone", "--bare", url, dest); err != nil {+ args := append(caCloneArgs(), "clone", "--bare", url, dest)+ if out, err := runGitCombinedOutputContext(ctx, args...); err != nil {// Clean up partial clone.os.RemoveAll(dest)return fmt.Errorf("git clone --bare: %s: %w", strings.TrimSpace(string(out)), err)}+ // Record the CA bundle before the refspec migration below fetches again.+ if err := configureRepoCABundleContext(ctx, dest); err != nil {+ os.RemoveAll(dest)+ return err+ }// `git clone --bare` populates refs/heads/* as a snapshot and defaults to// a mirror-style fetch refspec. Convert the bare repo to the standard// remote-tracking layout immediately so subsequent fetches write to@@ -815,6 +823,7 @@ func (c *Cache) CreateWorktreeContext(ctx context.Context, params WorktreeParams// ultimately succeeds. Stamping only on success would let a repo whose// checkouts keep failing age out from under the tasks still trying to use it.MarkUsed(barePath, c.logger)+ c.configureRepoCABundleLogged(ctx, barePath)// Fetch latest from origin. This also migrates the bare cache's refspec// to the modern remote-tracking layout on first run, so subsequent fetches@@ -1018,6 +1027,9 @@ func (c *Cache) createOrUpdateIsolatedCheckoutContext(ctx context.Context, barePif err := setIsolatedCheckoutOriginContext(ctx, checkoutPath, repoURL); err != nil {return nil, err}+ if err := configureRepoCABundleContext(ctx, checkoutPath); err != nil {+ return nil, err+ }// Idempotent, and required for a workdir that was first created while// the cache was still a full clone: without it, a checkout backed by a// blobless cache resolves missing blobs to nothing instead of fetching.@@ -1178,6 +1190,10 @@ func createIsolatedCheckoutContext(ctx context.Context, barePath, repoURL, checkif out, err := runGitCombinedOutputContext(ctx, "-C", checkoutPath, "remote", "add", "origin", repoURL); err != nil {return "", fmt.Errorf("add origin remote: %s: %w", strings.TrimSpace(string(out)), err)}+ // Before the first checkout, which may lazily fetch from origin.+ if err := configureRepoCABundleContext(ctx, checkoutPath); err != nil {+ return "", err+ }if isPartialCloneContext(ctx, barePath) {if err := configurePromisorRemoteContext(ctx, checkoutPath); err != nil {return "", errdiff --git a/server/internal/gitca/dirs_linux.go b/server/internal/gitca/dirs_linux.gonew file mode 100644index 0000000000..05695b574c--- /dev/null+++ b/server/internal/gitca/dirs_linux.go@@ -0,0 +1,43 @@+package gitca++import (+ "io/fs"+ "os"+ "path/filepath"+ "strings"+)++// certDirEnv matches crypto/x509's certDirEnv.+const certDirEnv = "SSL_CERT_DIR"++// systemCertDirectories matches crypto/x509's certDirectories on Linux. These+// hold the public roots every daemon already has, so they are not shared.+var systemCertDirectories = []string{+ "/etc/ssl/certs", // SLES10/SLES11+ "/etc/pki/tls/certs", // Fedora/RHEL+}++// readUniqueDirectoryEntries matches crypto/x509's helper of the same name:+// os.ReadDir without symlinks that point within the directory, which+// c_rehash creates as hash aliases of the real files.+func readUniqueDirectoryEntries(dir string) ([]fs.DirEntry, error) {+ files, err := os.ReadDir(dir)+ if err != nil {+ return nil, err+ }+ uniq := files[:0]+ for _, f := range files {+ if !isSameDirSymlink(f, dir) {+ uniq = append(uniq, f)+ }+ }+ return uniq, nil+}++func isSameDirSymlink(f fs.DirEntry, dir string) bool {+ if f.Type()&fs.ModeSymlink == 0 {+ return false+ }+ target, err := os.Readlink(filepath.Join(dir, f.Name()))+ return err == nil && !strings.Contains(target, "/")+}diff --git a/server/internal/gitca/dirs_other.go b/server/internal/gitca/dirs_other.gonew file mode 100644index 0000000000..1ce08aafc5--- /dev/null+++ b/server/internal/gitca/dirs_other.go@@ -0,0 +1,14 @@+//go:build !linux++package gitca++import "io/fs"++// crypto/x509 reads SSL_CERT_DIR only on Unix-like systems, with per-OS+// directory lists. The backend ships as a Linux image, so other platforms+// share nothing rather than guess at a list the standard library may not use.+const certDirEnv = ""++var systemCertDirectories []string++func readUniqueDirectoryEntries(string) ([]fs.DirEntry, error) { return nil, nil }diff --git a/server/internal/gitca/gitca.go b/server/internal/gitca/gitca.gonew file mode 100644index 0000000000..9486b8cba4--- /dev/null+++ b/server/internal/gitca/gitca.go@@ -0,0 +1,157 @@+// Package gitca extracts the private CA certificates an operator added to the+// backend's trust store through SSL_CERT_DIR, so the server can hand them to+// daemons. Daemons clone with the system git binary, which never reads the+// backend's SSL_CERT_DIR; without these certificates a repository on a host+// with an internal CA cannot sync.+package gitca++import (+ "bytes"+ "crypto/sha256"+ "crypto/x509"+ "encoding/hex"+ "encoding/pem"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+)++// MaxBundleSize caps the PEM sent to daemons. A handful of internal CAs is a+// few KB; anything near this limit is a misconfigured directory (for example+// the whole system store mounted under another path).+const MaxBundleSize = 256 << 10++// Load returns the PEM of every certificate in the non-system directories of+// SSL_CERT_DIR that crypto/x509 also trusts, or nil when there are none.+// Problems with individual files or certificates are logged and skipped so a+// bad file never blocks the server from starting.+func Load(logger *slog.Logger) []byte {+ certs, warnings := collect(os.Getenv(certDirEnv), systemCertDirectories)+ for _, w := range warnings {+ logger.Warn("git CA: skipping certificate", "detail", w)+ }+ if len(certs) == 0 {+ return nil+ }++ roots, err := x509.SystemCertPool()+ if err != nil {+ logger.Warn("git CA: system cert pool unavailable; not sharing SSL_CERT_DIR certificates with daemons", "error", err)+ return nil+ }++ var bundle bytes.Buffer+ fingerprints := make([]string, 0, len(certs))+ for _, cert := range certs {+ if err := trustedBy(cert, roots); err != nil {+ logger.Warn("git CA: certificate is not trusted by the backend; skipping", "subject", cert.Subject.String(), "error", err)+ continue+ }+ block := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})+ if bundle.Len()+len(block) > MaxBundleSize {+ logger.Warn("git CA: bundle size limit reached; skipping remaining certificates", "limit_bytes", MaxBundleSize)+ break+ }+ bundle.Write(block)+ fingerprints = append(fingerprints, fingerprint(cert))+ }+ if bundle.Len() == 0 {+ return nil+ }+ logger.Info("git CA: sharing SSL_CERT_DIR certificates with daemons", "count", len(fingerprints), "sha256", fingerprints)+ return bundle.Bytes()+}++// trustedBy reports whether crypto/x509 accepts cert as a trust anchor, so+// daemons receive exactly what the backend itself trusts even if collect ever+// drifts from the standard library's loader.+func trustedBy(cert *x509.Certificate, roots *x509.CertPool) error {+ _, err := cert.Verify(x509.VerifyOptions{+ Roots: roots,+ KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},+ })+ return err+}++// collect mirrors the SSL_CERT_DIR half of loadSystemRoots in+// crypto/x509/root_unix.go (Go 1.26): split on ":", read each directory while+// skipping symlinks that point within it, and parse every file as PEM. Unlike+// the standard library it skips the system directories, keeps the parsed+// certificates instead of a CertPool, and drops duplicates.+func collect(certDir string, systemDirs []string) ([]*x509.Certificate, []string) {+ if certDir == "" {+ return nil, nil+ }+ system := make(map[string]struct{}, len(systemDirs))+ for _, d := range systemDirs {+ system[filepath.Clean(d)] = struct{}{}+ }++ var (+ certs []*x509.Certificate+ warnings []string+ seen = map[[sha256.Size]byte]struct{}{}+ )+ for _, dir := range strings.Split(certDir, ":") {+ if dir == "" {+ continue+ }+ if _, ok := system[filepath.Clean(dir)]; ok {+ continue+ }+ entries, err := readUniqueDirectoryEntries(dir)+ if err != nil {+ if !os.IsNotExist(err) {+ warnings = append(warnings, fmt.Sprintf("read %s: %v", dir, err))+ }+ continue+ }+ for _, entry := range entries {+ path := filepath.Join(dir, entry.Name())+ data, err := os.ReadFile(path)+ if err != nil {+ // Subdirectories land here too; crypto/x509 ignores them the same way.+ continue+ }+ for _, cert := range parseCertificates(path, data, &warnings) {+ sum := sha256.Sum256(cert.Raw)+ if _, dup := seen[sum]; dup {+ continue+ }+ seen[sum] = struct{}{}+ certs = append(certs, cert)+ }+ }+ }+ return certs, warnings+}++// parseCertificates matches CertPool.AppendCertsFromPEM: non-CERTIFICATE+// blocks and certificates that fail to parse are skipped, not fatal.+func parseCertificates(path string, data []byte, warnings *[]string) []*x509.Certificate {+ var certs []*x509.Certificate+ for len(data) > 0 {+ var block *pem.Block+ block, data = pem.Decode(data)+ if block == nil {+ break+ }+ if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {+ continue+ }+ cert, err := x509.ParseCertificate(block.Bytes)+ if err != nil {+ *warnings = append(*warnings, fmt.Sprintf("parse %s: %v", path, err))+ continue+ }+ certs = append(certs, cert)+ }+ return certs+}++func fingerprint(cert *x509.Certificate) string {+ sum := sha256.Sum256(cert.Raw)+ return hex.EncodeToString(sum[:])+}diff --git a/server/internal/gitca/gitca_linux_test.go b/server/internal/gitca/gitca_linux_test.gonew file mode 100644index 0000000000..1dc53335c4--- /dev/null+++ b/server/internal/gitca/gitca_linux_test.go@@ -0,0 +1,172 @@+package gitca++import (+ "bytes"+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "io"+ "log/slog"+ "math/big"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func newTestCA(t *testing.T, name string, notAfter time.Time) []byte {+ t.Helper()+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ tmpl := &x509.Certificate{+ SerialNumber: big.NewInt(time.Now().UnixNano()),+ Subject: pkix.Name{CommonName: name},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: notAfter,+ IsCA: true,+ BasicConstraintsValid: true,+ KeyUsage: x509.KeyUsageCertSign,+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ if err != nil {+ t.Fatal(err)+ }+ return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})+}++func writeFile(t *testing.T, path string, data []byte) {+ t.Helper()+ if err := os.WriteFile(path, data, 0o644); err != nil {+ t.Fatal(err)+ }+}++func commonNames(certs []*x509.Certificate) []string {+ names := make([]string, 0, len(certs))+ for _, c := range certs {+ names = append(names, c.Subject.CommonName)+ }+ return names+}++func TestCollectSkipsSystemDirectories(t *testing.T) {+ system := t.TempDir()+ extra := t.TempDir()+ writeFile(t, filepath.Join(system, "public.pem"), newTestCA(t, "public", time.Now().Add(time.Hour)))+ writeFile(t, filepath.Join(extra, "internal.crt"), newTestCA(t, "internal", time.Now().Add(time.Hour)))++ certs, warnings := collect(system+":"+extra, []string{system + "/"})+ if got := commonNames(certs); len(got) != 1 || got[0] != "internal" {+ t.Fatalf("certs = %v, want [internal]", got)+ }+ if len(warnings) != 0 {+ t.Fatalf("warnings = %v, want none", warnings)+ }+}++func TestCollectEmptyEnvReturnsNothing(t *testing.T) {+ if certs, _ := collect("", nil); certs != nil {+ t.Fatalf("certs = %v, want nil", certs)+ }+}++func TestCollectMirrorsAppendCertsFromPEM(t *testing.T) {+ dir := t.TempDir()+ ca := newTestCA(t, "internal", time.Now().Add(time.Hour))+ second := newTestCA(t, "second", time.Now().Add(time.Hour))++ keyBlock := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: []byte("not a cert")})+ withHeaders := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Headers: map[string]string{"Proc-Type": "4,ENCRYPTED"}, Bytes: []byte("x")})+ broken := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("garbage")})++ writeFile(t, filepath.Join(dir, "bundle.pem"), bytes.Join([][]byte{keyBlock, ca, withHeaders, broken, second}, nil))+ writeFile(t, filepath.Join(dir, "notes.txt"), []byte("no PEM here"))+ if err := os.Mkdir(filepath.Join(dir, "subdir"), 0o755); err != nil {+ t.Fatal(err)+ }++ certs, warnings := collect(dir, nil)+ if got := commonNames(certs); len(got) != 2 || got[0] != "internal" || got[1] != "second" {+ t.Fatalf("certs = %v, want [internal second]", got)+ }+ if len(warnings) != 1 || !strings.Contains(warnings[0], "bundle.pem") {+ t.Fatalf("warnings = %v, want one parse warning for bundle.pem", warnings)+ }+}++func TestCollectDropsSameDirSymlinksAndDuplicates(t *testing.T) {+ dir := t.TempDir()+ other := t.TempDir()+ ca := newTestCA(t, "internal", time.Now().Add(time.Hour))+ writeFile(t, filepath.Join(dir, "internal.crt"), ca)+ // c_rehash style alias: same-dir symlink, skipped by crypto/x509.+ if err := os.Symlink("internal.crt", filepath.Join(dir, "abcd1234.0")); err != nil {+ t.Fatal(err)+ }+ // Same certificate in a second directory is shared once.+ writeFile(t, filepath.Join(other, "copy.crt"), ca)++ certs, _ := collect(dir+":"+other, nil)+ if len(certs) != 1 {+ t.Fatalf("got %d certificates, want 1", len(certs))+ }+}++func TestCollectMissingDirectoryIsSilent(t *testing.T) {+ certs, warnings := collect(filepath.Join(t.TempDir(), "missing"), nil)+ if len(certs) != 0 || len(warnings) != 0 {+ t.Fatalf("certs=%d warnings=%v, want none", len(certs), warnings)+ }+}++// crypto/x509 loads the system pool once per process, so the end-to-end check+// runs Load in a child process whose SSL_CERT_DIR is set before that happens.+const loadHelperEnv = "GITCA_TEST_LOAD_HELPER"++func TestLoadHelperProcess(t *testing.T) {+ if os.Getenv(loadHelperEnv) != "1" {+ t.Skip("helper process")+ }+ os.Stdout.Write(Load(slog.New(slog.NewTextHandler(io.Discard, nil))))+}++func runLoad(t *testing.T, certDir string) []byte {+ t.Helper()+ cmd := exec.Command(os.Args[0], "-test.run=^TestLoadHelperProcess$")+ cmd.Env = append(os.Environ(), loadHelperEnv+"=1", "SSL_CERT_DIR="+certDir)+ out, err := cmd.Output()+ if err != nil {+ t.Fatalf("helper failed: %v", err)+ }+ // The test framework prints PASS after the bundle.+ if i := bytes.LastIndex(out, []byte("-----END CERTIFICATE-----\n")); i >= 0 {+ return out[:i+len("-----END CERTIFICATE-----\n")]+ }+ return nil+}++func TestLoadSharesOnlyWhatGoTrusts(t *testing.T) {+ dir := t.TempDir()+ valid := newTestCA(t, "internal", time.Now().Add(time.Hour))+ expired := newTestCA(t, "expired", time.Now().Add(-time.Minute))+ writeFile(t, filepath.Join(dir, "internal.crt"), valid)+ writeFile(t, filepath.Join(dir, "expired.crt"), expired)++ got := runLoad(t, "/etc/ssl/certs:"+dir)+ if !bytes.Equal(got, valid) {+ t.Fatalf("Load() = %q, want only the valid internal CA", got)+ }+}++func TestLoadWithoutExtraDirectoriesSharesNothing(t *testing.T) {+ if got := runLoad(t, "/etc/ssl/certs"); len(got) != 0 {+ t.Fatalf("Load() = %q, want nothing", got)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 87a0f37d0d..66f013335b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -224,6 +224,9 @@ type daemonWorkspaceReposResponse struct {Repos []RepoData `json:"repos"`ReposVersion string `json:"repos_version"`Settings json.RawMessage `json:"settings,omitempty"`+ // CACerts carries the backend's extra CA certificates (PEM) for the+ // daemon's git. Older daemons ignore it.+ CACerts string `json:"ca_certs,omitempty"`}func normalizeWorkspaceRepos(repos []RepoData) []RepoData {@@ -272,12 +275,13 @@ func parseWorkspaceRepos(raw []byte) []RepoData {return normalizeWorkspaceRepos(repos)}-func workspaceReposResponse(workspaceID string, raw []byte, settingsRaw []byte) daemonWorkspaceReposResponse {+func workspaceReposResponse(workspaceID string, raw []byte, settingsRaw []byte, caCerts []byte) daemonWorkspaceReposResponse {repos := parseWorkspaceRepos(raw)resp := daemonWorkspaceReposResponse{WorkspaceID: workspaceID,Repos: repos,ReposVersion: workspaceReposVersion(repos),+ CACerts: string(caCerts),}if len(settingsRaw) > 0 {resp.Settings = json.RawMessage(settingsRaw)@@ -733,14 +737,18 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {"runtimes": resp,})- repoResp := workspaceReposResponse(req.WorkspaceID, ws.Repos, ws.Settings)+ repoResp := workspaceReposResponse(req.WorkspaceID, ws.Repos, ws.Settings, h.cfg.GitExtraCACerts)- writeJSON(w, http.StatusOK, map[string]any{+ body := map[string]any{"runtimes": resp,"repos": repoResp.Repos,"repos_version": repoResp.ReposVersion,"settings": repoResp.Settings,- })+ }+ if repoResp.CACerts != "" {+ body["ca_certs"] = repoResp.CACerts+ }+ writeJSON(w, http.StatusOK, body)}// mergeLegacyRuntimes folds every runtime row keyed on a prior hostname-derived@@ -917,7 +925,7 @@ func (h *Handler) GetDaemonWorkspaceRepos(w http.ResponseWriter, r *http.Requestreturn}- writeJSON(w, http.StatusOK, workspaceReposResponse(workspaceID, ws.Repos, ws.Settings))+ writeJSON(w, http.StatusOK, workspaceReposResponse(workspaceID, ws.Repos, ws.Settings, h.cfg.GitExtraCACerts))}// setRuntimeOffline flips a runtime offline, recording the daemon's reason whendiff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 8495d2e901..b4fca3ff65 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -1586,6 +1586,62 @@ func TestGetDaemonWorkspaceRepos_WithDaemonToken_WorkspaceMismatch(t *testing.T)testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusNotFound)}+func TestGetDaemonWorkspaceRepos_CACerts(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ prev := testHandler.cfg.GitExtraCACerts+ t.Cleanup(func() { testHandler.cfg.GitExtraCACerts = prev })++ call := func() map[string]any {+ req := newDaemonTokenRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil, testWorkspaceID, "test-daemon-mdt")+ req = withURLParam(req, "workspaceId", testWorkspaceID)+ var resp map[string]any+ testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusOK).JSON(&resp)+ return resp+ }++ testHandler.cfg.GitExtraCACerts = nil+ if _, ok := call()["ca_certs"]; ok {+ t.Fatal("ca_certs present without configured CAs")+ }++ const pemCerts = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"+ testHandler.cfg.GitExtraCACerts = []byte(pemCerts)+ if got := call()["ca_certs"]; got != pemCerts {+ t.Fatalf("ca_certs = %v, want configured PEM", got)+ }+}++func TestDaemonRegister_CACerts(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ prev := testHandler.cfg.GitExtraCACerts+ t.Cleanup(func() { testHandler.cfg.GitExtraCACerts = prev })++ const pemCerts = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"+ testHandler.cfg.GitExtraCACerts = []byte(pemCerts)++ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": "test-daemon-ca",+ "device_name": "test-device",+ "runtimes": []map[string]any{+ {"name": "test-runtime-ca", "type": "claude", "version": "1.0.0", "status": "online"},+ },+ }, testWorkspaceID, "test-daemon-ca")+ var resp map[string]any+ testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK).JSON(&resp)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE daemon_id = $1`, "test-daemon-ca")+ })++ if got := resp["ca_certs"]; got != pemCerts {+ t.Fatalf("ca_certs = %v, want configured PEM", got)+ }+}+func TestGetDaemonWorkspaceRepos_VersionIgnoresOrderAndDescription(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 393806a3e2..db9e9b6e79 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -155,6 +155,11 @@ type Config struct {// Surfaced through /api/config so self-hosted operators can confirm which// server build is deployed. Empty in dev builds.ServerVersion string+ // GitExtraCACerts is the PEM of the private CAs the operator added to the+ // backend's trust store through SSL_CERT_DIR (see internal/gitca). It is+ // handed to daemons with the workspace repos so their git can reach a+ // repository host the backend already trusts. Empty when none are set.+ GitExtraCACerts []byte}type cloudRuntimeProxy interface {