Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(action): support custom headers (#20131)

p0ny475627473d99
diff --git a/action/README.md b/action/README.md
index 77398125bf..85865d1ac0 100644
--- a/action/README.md
+++ b/action/README.md
@@ -45,6 +45,12 @@ These flags apply to the main `bytebase-action` command and its subcommands (`ch
- Default: `""` (empty string). If not provided via flag, reads from the `BYTEBASE_SERVICE_ACCOUNT_SECRET` environment variable.
- *Note: Setting the environment variable `BYTEBASE_SERVICE_ACCOUNT_SECRET` is the recommended way to handle the secret.*
+- **`--custom-header`**: A custom HTTP header to include in Bytebase API requests.
+ - Format: `Name: value`
+ - Can be specified multiple times.
+ - This is useful when the Bytebase URL is protected by a header-based access proxy such as Cloudflare Access.
+ - Example: `--custom-header="Cookie: CF_Authorization=${CF_AUTHORIZATION_COOKIE}"`
+
- **`--project`**: The target Bytebase project name.
- Format: `projects/{project}`
- Default: `projects/hr`
@@ -222,4 +228,3 @@ When using declarative mode, you must follow these steps:
-- Incorrect: unnamed index
CREATE INDEX ON public.users(email);
```
-
diff --git a/action/command/api.go b/action/command/api.go
index d03eb02dee..d45c0f10b8 100644
--- a/action/command/api.go
+++ b/action/command/api.go
@@ -36,6 +36,8 @@ type clientOptions struct {
timeout time.Duration
// retryConfig controls retry behavior for transient errors.
retryConfig *retryConfig
+ // customHeaders contains caller-provided headers for Bytebase API requests.
+ customHeaders http.Header
}
// defaultClientOptions returns the default client options.
@@ -90,6 +92,11 @@ func newClient(url, accessToken, serviceAccount, serviceAccountSecret string, op
}
httpClient = &http.Client{Timeout: timeout}
}
+ if len(opts.customHeaders) > 0 {
+ copiedClient := *httpClient
+ httpClient = &copiedClient
+ httpClient.Transport = newCustomHeaderTransport(httpClient.Transport, opts.customHeaders)
+ }
var tokenRefresher func(ctx context.Context) (string, error)
if accessToken != "" {
@@ -118,6 +125,37 @@ func newClient(url, accessToken, serviceAccount, serviceAccountSecret string, op
}, nil
}
+type customHeaderTransport struct {
+ base http.RoundTripper
+ headers http.Header
+}
+
+func newCustomHeaderTransport(base http.RoundTripper, headers http.Header) http.RoundTripper {
+ if base == nil {
+ base = http.DefaultTransport
+ }
+ return &customHeaderTransport{
+ base: base,
+ headers: headers.Clone(),
+ }
+}
+
+func (t *customHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ req = req.Clone(req.Context())
+ for name, values := range t.headers {
+ for _, value := range values {
+ req.Header.Add(name, value)
+ }
+ }
+ return t.base.RoundTrip(req)
+}
+
+func (t *customHeaderTransport) CloseIdleConnections() {
+ if transport, ok := t.base.(interface{ CloseIdleConnections() }); ok {
+ transport.CloseIdleConnections()
+ }
+}
+
func getTokenRefresher(httpClient connect.HTTPClient, email, password, url string) func(ctx context.Context) (string, error) {
// Create a separate auth client without interceptors to avoid circular dependencies
authClient := v1connect.NewAuthServiceClient(httpClient, url)
diff --git a/action/command/api_test.go b/action/command/api_test.go
index 6eba2dfd49..95a128b879 100644
--- a/action/command/api_test.go
+++ b/action/command/api_test.go
@@ -1,7 +1,10 @@
package command
import (
+ "io"
"net/http"
+ "net/http/httptest"
+ "strings"
"testing"
"time"
@@ -28,6 +31,175 @@ func TestNewClientWithOptionsUsesServiceAccountAuth(t *testing.T) {
require.Equal(t, "secret", client.serviceAccountSecret)
}
+func TestCustomHeaderFlag(t *testing.T) {
+ t.Parallel()
+
+ headers := http.Header{}
+ var headerErr error
+ flag := newCustomHeaderFlag(&headers, &headerErr)
+
+ require.NoError(t, flag.Set("Cookie: CF_Authorization=token"))
+ require.NoError(t, flag.Set("X-Request-Id: run-123"))
+ require.NoError(t, headerErr)
+ require.Equal(t, "CF_Authorization=token", headers.Get("Cookie"))
+ require.Equal(t, "run-123", headers.Get("X-Request-Id"))
+}
+
+func TestCustomHeaderFlagRejectsInvalidHeaders(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ value string
+ }{
+ {
+ name: "missing separator",
+ value: "Cookie",
+ },
+ {
+ name: "empty name",
+ value: ": value",
+ },
+ {
+ name: "newline in value",
+ value: "Cookie: value\nX-Other: injected",
+ },
+ {
+ name: "authorization is managed by bytebase action",
+ value: "Authorization: Bearer token",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ headers := http.Header{}
+ var headerErr error
+ require.NoError(t, newCustomHeaderFlag(&headers, &headerErr).Set(tt.value))
+ require.Error(t, headerErr)
+ })
+ }
+}
+
+func TestCustomHeaderFlagDoesNotLeakHeaderValueInFormatError(t *testing.T) {
+ t.Parallel()
+
+ headers := http.Header{}
+ var headerErr error
+ secret := "Cookie CF_Authorization=secret-token"
+ require.NoError(t, newCustomHeaderFlag(&headers, &headerErr).Set(secret))
+ require.Error(t, headerErr)
+ require.NotContains(t, headerErr.Error(), "secret-token")
+ require.NotContains(t, headerErr.Error(), secret)
+}
+
+func TestCustomHeadersAreSentOnLoginRequest(t *testing.T) {
+ t.Parallel()
+
+ customHeaders := http.Header{}
+ customHeaders.Set("Cookie", "CF_Authorization=token")
+ customHeaders.Set("X-Request-Id", "run-123")
+
+ transport := roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ require.Equal(t, "CF_Authorization=token", req.Header.Get("Cookie"))
+ require.Equal(t, "run-123", req.Header.Get("X-Request-Id"))
+ return &http.Response{
+ StatusCode: http.StatusUnauthorized,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader("unauthorized")),
+ Request: req,
+ }, nil
+ })
+
+ httpClient := &http.Client{Transport: transport}
+ client, err := newClient("https://example.com", "", "[email protected]", "secret", clientOptions{
+ httpClient: httpClient,
+ customHeaders: customHeaders,
+ })
+ require.NoError(t, err)
+ t.Cleanup(client.close)
+ refreshToken := getTokenRefresher(client.httpClient, "[email protected]", "secret", "https://example.com")
+
+ _, err = refreshToken(t.Context())
+ require.Error(t, err)
+}
+
+func TestNewClientDoesNotMutateProvidedHTTPClientTransport(t *testing.T) {
+ t.Parallel()
+
+ customHeaders := http.Header{}
+ customHeaders.Set("Cookie", "CF_Authorization=token")
+ transport := &closeIdleRoundTripper{}
+ httpClient := &http.Client{Transport: transport}
+
+ client, err := newClient("https://example.com", "token", "", "", clientOptions{
+ httpClient: httpClient,
+ customHeaders: customHeaders,
+ })
+ require.NoError(t, err)
+ t.Cleanup(client.close)
+
+ require.Same(t, transport, httpClient.Transport)
+ require.NotSame(t, httpClient, client.httpClient)
+}
+
+func TestCustomHeaderTransportAddsCustomHeaders(t *testing.T) {
+ t.Parallel()
+
+ customHeaders := http.Header{}
+ customHeaders.Set("Cookie", "CF_Authorization=token")
+ customHeaders.Set("X-Request-Id", "run-123")
+
+ transport := newCustomHeaderTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ require.Equal(t, "CF_Authorization=token", req.Header.Get("Cookie"))
+ require.Equal(t, "run-123", req.Header.Get("X-Request-Id"))
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader("ok")),
+ Request: req,
+ }, nil
+ }), customHeaders)
+
+ resp, err := transport.RoundTrip(httptest.NewRequest(http.MethodGet, "https://example.com", nil))
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+}
+
+func TestCustomHeaderTransportClosesIdleConnections(t *testing.T) {
+ t.Parallel()
+
+ base := &closeIdleRoundTripper{}
+ transport := newCustomHeaderTransport(base, http.Header{})
+ transport.(interface{ CloseIdleConnections() }).CloseIdleConnections()
+ require.True(t, base.closed)
+}
+
+type roundTripFunc func(req *http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
+type closeIdleRoundTripper struct {
+ closed bool
+}
+
+func (*closeIdleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader("ok")),
+ Request: req,
+ }, nil
+}
+
+func (t *closeIdleRoundTripper) CloseIdleConnections() {
+ t.closed = true
+}
+
func TestNewClientWithAccessTokenUsesAccessTokenAuth(t *testing.T) {
t.Parallel()
diff --git a/action/command/root.go b/action/command/root.go
index 4ae5cc866c..c2f469dbdd 100644
--- a/action/command/root.go
+++ b/action/command/root.go
@@ -3,10 +3,14 @@ package command
import (
"context"
"log/slog"
+ "net/http"
+ "net/textproto"
+ "strings"
"time"
"github.com/pkg/errors"
"github.com/spf13/cobra"
+ "golang.org/x/net/http/httpguts"
"github.com/bytebase/bytebase/action/command/cloud"
"github.com/bytebase/bytebase/action/command/validation"
@@ -28,6 +32,7 @@ func NewRootCommand(w *world.World) *cobra.Command {
cmd.PersistentFlags().StringVar(&w.ServiceAccount, "service-account", "", "Bytebase Service account")
cmd.PersistentFlags().StringVar(&w.ServiceAccountSecret, "service-account-secret", "", "Bytebase Service account secret")
cmd.PersistentFlags().StringVar(&w.AccessToken, "access-token", "", "Bytebase access token (alternative to service account auth, e.g. from workload identity exchange)")
+ cmd.PersistentFlags().Var(newCustomHeaderFlag(&w.CustomHeaders, &w.CustomHeaderError), "custom-header", "Custom HTTP header for Bytebase API requests, in 'Name: value' format. Can be specified multiple times")
cmd.PersistentFlags().StringVar(&w.Project, "project", "projects/hr", "Bytebase project")
cmd.PersistentFlags().StringSliceVar(&w.Targets, "targets", []string{"instances/test-sample-instance/databases/hr_test", "instances/prod-sample-instance/databases/hr_prod"}, "Bytebase targets. Either one or more databases or a single databaseGroup")
cmd.PersistentFlags().StringVar(&w.FilePattern, "file-pattern", "", "File pattern to glob migration files")
@@ -42,6 +47,10 @@ func rootPreRun(w *world.World) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, _ []string) error {
w.Logger = slog.New(slog.NewTextHandler(cmd.ErrOrStderr(), nil))
+ if w.CustomHeaderError != nil {
+ return w.CustomHeaderError
+ }
+
// Validate all flags and environment variables
if err := validation.ValidateFlags(w); err != nil {
return errors.Wrapf(err, "failed to validate flags")
@@ -62,6 +71,7 @@ func newClientFromWorld(w *world.World) (*client, error) {
if w.Timeout > 0 {
options.timeout = w.Timeout
}
+ options.customHeaders = w.CustomHeaders
// Access tokens take precedence when both auth modes are populated.
if w.AccessToken != "" {
@@ -70,6 +80,57 @@ func newClientFromWorld(w *world.World) (*client, error) {
return newClient(w.URL, "", w.ServiceAccount, w.ServiceAccountSecret, options)
}
+type customHeaderFlag struct {
+ headers *http.Header
+ err *error
+}
+
+func newCustomHeaderFlag(headers *http.Header, err *error) *customHeaderFlag {
+ if *headers == nil {
+ *headers = http.Header{}
+ }
+ return &customHeaderFlag{headers: headers, err: err}
+}
+
+func (f *customHeaderFlag) Set(value string) error {
+ name, headerValue, ok := strings.Cut(value, ":")
+ if !ok {
+ *f.err = errors.Errorf("invalid custom-header, must be in 'Name: value' format")
+ return nil
+ }
+
+ name = textproto.CanonicalMIMEHeaderKey(strings.TrimSpace(name))
+ if !httpguts.ValidHeaderFieldName(name) {
+ *f.err = errors.Errorf("invalid custom-header name")
+ return nil
+ }
+ if strings.EqualFold(name, "Authorization") {
+ *f.err = errors.Errorf("custom-header Authorization is not allowed because bytebase-action manages Bytebase authorization")
+ return nil
+ }
+ if !httpguts.ValidHeaderFieldValue(headerValue) {
+ *f.err = errors.Errorf("invalid custom-header value")
+ return nil
+ }
+
+ f.headers.Add(name, strings.TrimSpace(headerValue))
+ return nil
+}
+
+func (f *customHeaderFlag) String() string {
+ if f == nil || f.headers == nil {
+ return ""
+ }
+ if len(*f.headers) == 0 {
+ return ""
+ }
+ return "[redacted]"
+}
+
+func (*customHeaderFlag) Type() string {
+ return "header"
+}
+
func checkVersionCompatibility(w *world.World, client *client, cliVersion string) {
if cliVersion == "unknown" {
w.Logger.Warn("CLI version unknown, unable to check compatibility")
diff --git a/action/world/world.go b/action/world/world.go
index fd7f82404a..e2375c4aab 100644
--- a/action/world/world.go
+++ b/action/world/world.go
@@ -2,6 +2,7 @@ package world
import (
"log/slog"
+ "net/http"
"time"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
@@ -23,6 +24,8 @@ type World struct {
ServiceAccount string
ServiceAccountSecret string
AccessToken string // Alternative to service account auth, e.g. from workload identity exchange
+ CustomHeaders http.Header
+ CustomHeaderError error
Project string // projects/{project}
Targets []string
FilePattern string