Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(vcs): explain untrusted TLS certificates and trust private CAs via Helm (MUL-7639) (#8761)

Bohan Jiang4f5fbc92164b
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index fdb5623f43..8d666ac846 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -263,6 +263,8 @@ When developing from a checkout, use the local chart path instead:
helm install multica deploy/helm/multica -n multica
```
+If the backend has to reach services whose certificates come from an internal CA, such as a self-hosted Gitea, set `backend.extraCACerts.configMap`. See [Advanced Configuration → Private CA Certificates](SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional).
+
Watch the pods come up:
```bash
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 441b6f9567..97db85239f 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -177,6 +177,71 @@ rewrite configuration. Its backend fallback therefore accepts
`BACKEND_PORT` → `API_PORT` → `SERVER_PORT` → `8080`, while an explicit
`REMOTE_API_URL` or `NEXT_PUBLIC_API_URL` still takes priority.
+### Private CA Certificates (Optional)
+
+The backend checks the TLS certificates of the HTTPS services it calls against
+the system trust store in its image. A service whose certificate comes from an
+internal CA — for example a [self-hosted Gitea, Forgejo, or GitLab](https://multica.ai/docs/vcs-integration)
+— fails until the backend trusts that CA. Connecting such a Git provider reports
+that its certificate is signed by a certificate authority the server does not
+trust.
+
+Add the CA to the backend's trust store rather than turning verification off.
+The backend is a Go program: on Linux it loads the system certificate bundle
+plus every PEM file in the directories listed in `SSL_CERT_DIR`. Mount the CA
+into its own read-only directory and list it after the system directory:
+
+```
+SSL_CERT_DIR=/etc/ssl/certs:/etc/multica/ca-certs
+```
+
+**Kubernetes (Helm):** create a ConfigMap whose keys are PEM files, then point
+`backend.extraCACerts.configMap` at it. The chart mounts it at
+`/etc/multica/ca-certs` and sets `SSL_CERT_DIR` as above.
+
+```bash
+kubectl -n multica create configmap multica-extra-ca --from-file=internal-ca.crt
+helm upgrade multica oci://ghcr.io/multica-ai/charts/multica \
+ --version <chart-version> -n multica --reuse-values \
+ --set backend.extraCACerts.configMap=multica-extra-ca
+```
+
+**Docker Compose:** put the PEM files in a directory next to
+`docker-compose.selfhost.yml` (here `./ca-certs`) and add an override file,
+`docker-compose.ca.yml`:
+
+```yaml
+services:
+ backend:
+ environment:
+ SSL_CERT_DIR: /etc/ssl/certs:/etc/multica/ca-certs
+ volumes:
+ - ./ca-certs:/etc/multica/ca-certs:ro
+```
+
+```bash
+docker compose -f docker-compose.selfhost.yml -f docker-compose.ca.yml up -d backend
+```
+
+Pass both files every time you run a command that recreates the backend. A
+command with only `docker-compose.selfhost.yml`, such as `make selfhost`,
+recreates the backend without the CA.
+
+Things to know:
+
+- **The backend reads the CA only when it starts.** After you add or replace a
+ CA file, restart the backend: `kubectl -n multica rollout restart deploy/multica-backend`,
+ or `docker compose -f docker-compose.selfhost.yml -f docker-compose.ca.yml restart backend`.
+ With Compose, `up -d` is not enough here: the container's configuration has
+ not changed, so Compose keeps the running container. With Helm, a
+ `helm upgrade` also restarts the backend when the ConfigMap has changed.
+- **The CA applies to the whole backend process**, not only the Git provider
+ integration: every outbound TLS client in the backend that uses the system
+ trust store trusts it too.
+- **Only the trust problem is fixed.** An expired certificate, or one that does
+ not cover the host name in the URL, is still rejected; fix the certificate
+ itself.
+
### WeCom frame tracing
| Variable | Default | Description |
diff --git a/apps/docs/content/docs/vcs-integration.fr.mdx b/apps/docs/content/docs/vcs-integration.fr.mdx
index e96760fa36..b3aa5d2ca9 100644
--- a/apps/docs/content/docs/vcs-integration.fr.mdx
+++ b/apps/docs/content/docs/vcs-integration.fr.mdx
@@ -59,6 +59,12 @@ Définissez `MULTICA_PUBLIC_URL` sur l'URL de base publique du serveur pour que
Le secret du webhook n'est affiché qu'une seule fois. Copiez-le avant de quitter la page. Reconnecter la même instance régénère le jeton et le secret.
</Callout>
+### 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).
+
+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.
+
## Enregistrer le webhook
Sur le dépôt (ou sur l'organisation/le groupe, pour couvrir tous les dépôts) :
diff --git a/apps/docs/content/docs/vcs-integration.ja.mdx b/apps/docs/content/docs/vcs-integration.ja.mdx
index 5e678bf8ba..7ad88a79f4 100644
--- a/apps/docs/content/docs/vcs-integration.ja.mdx
+++ b/apps/docs/content/docs/vcs-integration.ja.mdx
@@ -54,6 +54,12 @@ MULTICA_VCS_SECRET_KEY=<base64 32 バイト鍵>
Webhook secret は一度しか表示されません。ページを離れる前にコピーしてください。同じインスタンスへ再接続すると、トークンと secret がローテーションされます。
</Callout>
+### プライベート 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) を参照してください。
+
+接続リクエストにはアクセストークンが含まれるため、Multica には証明書の検証をスキップするオプションはありません。証明書がホスト名と一致しない、または検証に失敗した(例: 有効期限切れ)と表示された場合は、証明書そのものを修正してください。CA を信頼しても解決しません。
+
## Webhook を登録
リポジトリ(または全リポジトリを対象にする組織/グループ)で設定します。
diff --git a/apps/docs/content/docs/vcs-integration.ko.mdx b/apps/docs/content/docs/vcs-integration.ko.mdx
index c6ecf4dd3f..2f08bc0455 100644
--- a/apps/docs/content/docs/vcs-integration.ko.mdx
+++ b/apps/docs/content/docs/vcs-integration.ko.mdx
@@ -54,6 +54,12 @@ MULTICA_VCS_SECRET_KEY=<base64 32바이트 키>
Webhook secret은 한 번만 표시됩니다. 페이지를 떠나기 전에 복사하세요. 같은 인스턴스에 다시 연결하면 token과 secret이 교체됩니다.
</Callout>
+### 사설 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)를 참고하세요.
+
+연결 요청에는 액세스 token이 포함되므로 Multica는 인증서 검증을 건너뛰는 옵션을 제공하지 않습니다. 인증서가 호스트 이름과 일치하지 않거나 검증에 실패했다는(예: 만료) 메시지가 나오면 인증서 자체를 고쳐야 합니다. CA를 신뢰하는 것으로는 해결되지 않습니다.
+
## Webhook 등록
저장소에서 설정합니다. 모든 저장소를 포함하려면 조직 또는 그룹에서 설정할 수도 있습니다.
diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdx
index 6442a3c13f..dc6a17af06 100644
--- a/apps/docs/content/docs/vcs-integration.mdx
+++ b/apps/docs/content/docs/vcs-integration.mdx
@@ -59,6 +59,12 @@ Set `MULTICA_PUBLIC_URL` to the server's public base URL so Multica can show a r
The webhook secret is shown only once. Copy it before leaving the page. Reconnecting the same instance rotates the token and secret.
</Callout>
+### 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.
+
+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.
+
## Register the webhook
On the repository (or organisation/group, to cover every repo):
diff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdx
index 82dd71ef01..d618e9d079 100644
--- a/apps/docs/content/docs/vcs-integration.zh.mdx
+++ b/apps/docs/content/docs/vcs-integration.zh.mdx
@@ -54,6 +54,12 @@ MULTICA_VCS_SECRET_KEY=<base64 32 字节密钥>
Webhook 密钥只显示一次,请在离开页面前复制。重新连接同一实例会轮换令牌与密钥。
</Callout>
+### 实例使用私有 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)。
+
+Multica 不提供跳过证书校验的选项,因为连接请求会携带你的访问令牌。如果提示证书与主机名不匹配,或证书校验失败(例如已过期),需要修复证书本身,信任 CA 解决不了。
+
## 注册 Webhook
在仓库(或组织/群组,以覆盖所有仓库):
diff --git a/deploy/helm/multica/templates/backend.yaml b/deploy/helm/multica/templates/backend.yaml
index 21e678f798..bf34da6977 100644
--- a/deploy/helm/multica/templates/backend.yaml
+++ b/deploy/helm/multica/templates/backend.yaml
@@ -1,4 +1,6 @@
{{- $backendImageTag := default .Chart.AppVersion .Values.images.backend.tag -}}
+{{- /* `helm upgrade --reuse-values` from a chart without extraCACerts carries no such key. */ -}}
+{{- $extraCACerts := (default dict .Values.backend.extraCACerts).configMap -}}
{{- if .Values.backend.uploads.persistence.enabled -}}
apiVersion: v1
kind: PersistentVolumeClaim
@@ -52,6 +54,10 @@ spec:
# rendered value there is a placeholder; on a real install/upgrade it
# reflects the actual Secret and rolls pods on rotation.
checksum/secret: {{ (lookup "v1" "Secret" .Release.Namespace .Values.existingSecret).data | toYaml | sha256sum }}
+ {{- if $extraCACerts }}
+ # Same lookup pattern: the backend reads extra CAs only at startup.
+ checksum/extra-ca-certs: {{ (lookup "v1" "ConfigMap" .Release.Namespace $extraCACerts).data | toYaml | sha256sum }}
+ {{- end }}
labels:
{{- include "multica.labels" . | nindent 8 }}
app.kubernetes.io/component: backend
@@ -68,15 +74,31 @@ spec:
name: {{ .Release.Name }}-config
- secretRef:
name: {{ .Values.existingSecret }}
- {{- if not .Values.postgres.external.enabled }}
+ {{- if or (not .Values.postgres.external.enabled) $extraCACerts }}
env:
+ {{- if not .Values.postgres.external.enabled }}
- name: DATABASE_URL
value: {{ include "multica.databaseUrl" . | quote }}
+ {{- end }}
+ {{- if $extraCACerts }}
+ # Go loads the system bundle file plus every file in these
+ # directories. SSL_CERT_DIR replaces the default directory list,
+ # so the system directory stays in it alongside the extra CAs.
+ - name: SSL_CERT_DIR
+ value: /etc/ssl/certs:/etc/multica/ca-certs
+ {{- end }}
{{- end }}
- {{- if .Values.backend.uploads.persistence.enabled }}
+ {{- if or .Values.backend.uploads.persistence.enabled $extraCACerts }}
volumeMounts:
+ {{- if .Values.backend.uploads.persistence.enabled }}
- name: uploads
mountPath: /app/data/uploads
+ {{- end }}
+ {{- if $extraCACerts }}
+ - name: extra-ca-certs
+ mountPath: /etc/multica/ca-certs
+ readOnly: true
+ {{- end }}
{{- end }}
# The entrypoint runs `./migrate up` before serving traffic. On a
# cold cluster (Postgres still coming up) this can take minutes. The
@@ -114,11 +136,18 @@ spec:
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
- {{- if .Values.backend.uploads.persistence.enabled }}
+ {{- if or .Values.backend.uploads.persistence.enabled $extraCACerts }}
volumes:
+ {{- if .Values.backend.uploads.persistence.enabled }}
- name: uploads
persistentVolumeClaim:
claimName: {{ include "multica.backend.fullname" . }}-uploads
+ {{- end }}
+ {{- if $extraCACerts }}
+ - name: extra-ca-certs
+ configMap:
+ name: {{ $extraCACerts }}
+ {{- end }}
{{- end }}
---
apiVersion: v1
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index a44fc560fc..1ef312a814 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -108,6 +108,16 @@ backend:
# backend replicas without S3.
accessModes:
- ReadWriteOnce
+ # Extra CA certificates for the backend's outbound HTTPS — e.g. a self-hosted
+ # Gitea / Forgejo / GitLab whose certificate comes from an internal CA. Set
+ # 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.
+ extraCACerts:
+ configMap: ""
# All non-secret backend env. Secret values come from `existingSecret`.
config:
# Optional container-loopback maintenance API; empty disables it. Never expose via Service/Ingress.
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index 39ac46d09f..b4f70b7702 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -52,6 +52,27 @@ require_rendered_value "$default_backend" 'failureThreshold: 60'
liveness_block="$(sed -n '/livenessProbe:/,/resources:/p' <<<"$default_backend")"
require_rendered_value "$liveness_block" 'path: /health'
reject_rendered_value "$liveness_block" 'path: /healthz'
+reject_rendered_value "$default_backend" 'SSL_CERT_DIR'
+reject_rendered_value "$default_backend" 'extra-ca-certs'
+
+# `helm upgrade --reuse-values` from a chart that predates extraCACerts renders
+# without the key at all; that must still render, with no extra trust.
+legacy_backend="$(
+ helm template multica "$CHART_DIR" \
+ --show-only templates/backend.yaml \
+ --set backend.extraCACerts=null
+)"
+reject_rendered_value "$legacy_backend" 'SSL_CERT_DIR'
+
+extra_ca_backend="$(
+ helm template multica "$CHART_DIR" \
+ --show-only templates/backend.yaml \
+ --set backend.extraCACerts.configMap=internal-ca
+)"
+require_rendered_value "$extra_ca_backend" 'value: /etc/ssl/certs:/etc/multica/ca-certs'
+require_rendered_value "$extra_ca_backend" 'mountPath: /etc/multica/ca-certs'
+require_rendered_value "$extra_ca_backend" 'name: internal-ca'
+require_rendered_value "$extra_ca_backend" 'mountPath: /app/data/uploads'
disabled_config="$(
helm template multica "$CHART_DIR" \
diff --git a/server/internal/handler/vcs.go b/server/internal/handler/vcs.go
index ea0f301e16..a383112acc 100644
--- a/server/internal/handler/vcs.go
+++ b/server/internal/handler/vcs.go
@@ -2,10 +2,13 @@ package handler
import (
"crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
+ "log/slog"
"net/http"
"net/url"
"strings"
@@ -197,7 +200,12 @@ func (h *Handler) ConnectVCS(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "the provider rejected the access token")
return
}
- writeError(w, http.StatusBadGateway, "could not reach the provider instance")
+ slog.Warn("vcs: connect validation failed",
+ "workspace_id", workspaceID,
+ "provider", provider.Kind(),
+ "host", parsed.Host,
+ "err", err)
+ writeError(w, http.StatusBadGateway, vcsValidationFailureMessage(err))
return
}
@@ -244,6 +252,28 @@ func (h *Handler) ConnectVCS(w http.ResponseWriter, r *http.Request) {
})
}
+// vcsValidationFailureMessage explains a ValidateToken failure other than a
+// rejected token. A certificate failure means the instance answered but this
+// server did not trust its TLS certificate, so it gets its own message instead
+// of "could not reach", which sends the admin chasing the network. An
+// untrusted CA is fixable by trusting the CA; a hostname or expiry failure
+// means the certificate itself needs fixing.
+func vcsValidationFailureMessage(err error) string {
+ var unknownCA x509.UnknownAuthorityError
+ var hostname x509.HostnameError
+ var verification *tls.CertificateVerificationError
+ switch {
+ case errors.As(err, &unknownCA):
+ return "the provider's TLS certificate is signed by a certificate authority this server does not trust; add that CA to the Multica server's trust store"
+ case errors.As(err, &hostname):
+ return "the provider's TLS certificate does not match the instance URL's host name"
+ case errors.As(err, &verification):
+ return "the provider's TLS certificate failed verification (for example, it has expired)"
+ default:
+ return "could not reach the provider instance"
+ }
+}
+
// DeleteVCSConnection (DELETE /workspaces/{id}/vcs/connections/{connectionId}).
func (h *Handler) DeleteVCSConnection(w http.ResponseWriter, r *http.Request) {
workspaceID := chi.URLParam(r, "id")
diff --git a/server/internal/handler/vcs_test.go b/server/internal/handler/vcs_test.go
index 9fac3680e2..1c57ae076d 100644
--- a/server/internal/handler/vcs_test.go
+++ b/server/internal/handler/vcs_test.go
@@ -2,13 +2,18 @@ package handler
import (
"context"
+ "crypto/tls"
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
+ "strings"
"sync/atomic"
"testing"
+ "time"
"github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/testutil"
)
func vcsHandlerRequest(method, path string, body any, connectionID string) *http.Request {
@@ -173,3 +178,89 @@ func TestRotateVCSConnectionWebhookHonorsDeploymentSwitch(t *testing.T) {
t.Fatal("enabled RotateVCSConnectionWebhook must replace the stored secret")
}
}
+
+// TestConnectVCSReportsUntrustedCertificate covers a Gitea behind a private or
+// self-signed CA: the connect must fail as a certificate problem, not as an
+// unreachable instance, and must not store a connection.
+func TestConnectVCSReportsUntrustedCertificate(t *testing.T) {
+ var reached atomic.Int32
+ provider := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ reached.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"login":"vcs-test-user"}`))
+ }))
+ defer provider.Close()
+
+ withVCSBox(t)
+ t.Cleanup(func() { cleanupVCS(context.Background(), "") })
+ req := vcsHandlerRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/vcs/connections", map[string]any{
+ "provider": "gitea",
+ "instance_url": provider.URL,
+ "access_token": "test-token",
+ }, "")
+ var resp struct {
+ Error string `json:"error"`
+ }
+ testutil.Call(t, testHandler.ConnectVCS, req).Want(http.StatusBadGateway).JSON(&resp)
+ if !strings.Contains(resp.Error, "certificate authority") {
+ t.Fatalf("expected an untrusted-certificate message, got %q", resp.Error)
+ }
+ if got := reached.Load(); got != 0 {
+ t.Fatalf("the TLS handshake must fail before any request is served, got %d", got)
+ }
+ var count int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT count(*) FROM vcs_connection WHERE workspace_id = $1 AND instance_url = $2`,
+ testWorkspaceID, provider.URL,
+ ).Scan(&count); err != nil {
+ t.Fatalf("count VCS connections: %v", err)
+ }
+ if count != 0 {
+ t.Fatalf("a failed connect must not store a connection, got %d rows", count)
+ }
+}
+
+// TestVCSValidationFailureMessage drives real handshakes so each case matches
+// the error shape crypto/tls actually returns, wrapped the way providers wrap
+// it.
+func TestVCSValidationFailureMessage(t *testing.T) {
+ srv := httptest.NewTLSServer(http.NotFoundHandler())
+ defer srv.Close()
+ // srv.Client() trusts the test certificate, which covers 127.0.0.1 and
+ // example.com and is valid until 2084.
+ trusting := func(adjust func(*tls.Config)) *http.Client {
+ transport := srv.Client().Transport.(*http.Transport).Clone()
+ adjust(transport.TLSClientConfig)
+ return &http.Client{Transport: transport}
+ }
+ closed := httptest.NewServer(http.NotFoundHandler())
+ closedURL := closed.URL
+ closed.Close()
+
+ cases := []struct {
+ name string
+ client *http.Client
+ url string
+ want string
+ }{
+ {"untrusted CA", &http.Client{}, srv.URL, "certificate authority this server does not trust"},
+ {"hostname mismatch", trusting(func(c *tls.Config) { c.ServerName = "gitea.internal.test" }), srv.URL, "does not match"},
+ {"expired", trusting(func(c *tls.Config) {
+ c.Time = func() time.Time { return time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC) }
+ }), srv.URL, "failed verification"},
+ {"unreachable", &http.Client{}, closedURL, "could not reach the provider instance"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ resp, err := tc.client.Get(tc.url)
+ if err == nil {
+ resp.Body.Close()
+ t.Fatal("expected the request to fail")
+ }
+ got := vcsValidationFailureMessage(fmt.Errorf("gitea: request: %w", err))
+ if !strings.Contains(got, tc.want) {
+ t.Fatalf("error %v: got message %q, want it to contain %q", err, got, tc.want)
+ }
+ })
+ }
+}