|
| 1 | +package providercache_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net" |
| 9 | + "net/http" |
| 10 | + "net/http/httptest" |
| 11 | + "strings" |
| 12 | + "sync/atomic" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "github.com/google/uuid" |
| 16 | + "github.com/gruntwork-io/terragrunt/internal/providercache" |
| 17 | + "github.com/gruntwork-io/terragrunt/internal/tf/cache" |
| 18 | + "github.com/gruntwork-io/terragrunt/internal/tf/cache/handlers" |
| 19 | + "github.com/gruntwork-io/terragrunt/internal/tf/cache/services" |
| 20 | + "github.com/gruntwork-io/terragrunt/internal/tf/cliconfig" |
| 21 | + "github.com/gruntwork-io/terragrunt/test/helpers" |
| 22 | + "github.com/gruntwork-io/terragrunt/test/helpers/logger" |
| 23 | + "github.com/stretchr/testify/assert" |
| 24 | + "github.com/stretchr/testify/require" |
| 25 | + "golang.org/x/sync/errgroup" |
| 26 | +) |
| 27 | + |
| 28 | +// fakeDiscoverer pretends the upstream registry advertised the given modules.v1 |
| 29 | +// path during well-known discovery. Used to bypass real network discovery in tests. |
| 30 | +type fakeDiscoverer struct { |
| 31 | + modulesV1 string |
| 32 | +} |
| 33 | + |
| 34 | +func (d *fakeDiscoverer) DiscoveryURL(_ context.Context, _ string) (*handlers.RegistryURLs, error) { |
| 35 | + return &handlers.RegistryURLs{ |
| 36 | + ProvidersV1: "/v1/providers", |
| 37 | + ModulesV1: d.modulesV1, |
| 38 | + }, nil |
| 39 | +} |
| 40 | + |
| 41 | +// TestNestedModuleCredentials reproduces issue #5970: when TG_PROVIDER_CACHE is on, |
| 42 | +// the cache server was forwarding nested module-registry requests with its own |
| 43 | +// x-api-key bearer token instead of the user's real upstream credentials, causing |
| 44 | +// 403s. The cache server must strip its own auth header and re-inject the user's |
| 45 | +// configured credentials when proxying modules.v1 requests upstream. |
| 46 | +func TestNestedModuleCredentials(t *testing.T) { |
| 47 | + t.Parallel() |
| 48 | + |
| 49 | + const realUserToken = "real-user-token" |
| 50 | + |
| 51 | + var ( |
| 52 | + upstreamHits atomic.Int32 |
| 53 | + upstreamAuth atomic.Value |
| 54 | + upstreamReject atomic.Int32 |
| 55 | + ) |
| 56 | + |
| 57 | + const versionsBody = `{"modules":[{"versions":[{"version":"0.1.0"},{"version":"0.2.0"}]}]}` |
| 58 | + |
| 59 | + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 60 | + auth := r.Header.Get("Authorization") |
| 61 | + upstreamAuth.Store(auth) |
| 62 | + upstreamHits.Add(1) |
| 63 | + |
| 64 | + if auth != "Bearer "+realUserToken { |
| 65 | + upstreamReject.Add(1) |
| 66 | + w.WriteHeader(http.StatusForbidden) |
| 67 | + |
| 68 | + return |
| 69 | + } |
| 70 | + |
| 71 | + switch r.URL.Path { |
| 72 | + case "/v1/modules/private/lambda/aws/versions": |
| 73 | + w.Header().Set("Content-Type", "application/json") |
| 74 | + |
| 75 | + if _, err := io.WriteString(w, versionsBody); err != nil { |
| 76 | + t.Errorf("upstream write failed: %v", err) |
| 77 | + } |
| 78 | + default: |
| 79 | + w.WriteHeader(http.StatusNotFound) |
| 80 | + } |
| 81 | + })) |
| 82 | + t.Cleanup(upstream.Close) |
| 83 | + |
| 84 | + registryName := strings.TrimPrefix(upstream.URL, "http://") |
| 85 | + |
| 86 | + // Build a credentials source that has the user's real token for the upstream host. |
| 87 | + cliCfg := &cliconfig.Config{ |
| 88 | + Credentials: []cliconfig.ConfigCredentials{ |
| 89 | + {Name: "127.0.0.1", Token: realUserToken}, |
| 90 | + }, |
| 91 | + } |
| 92 | + credsSource := cliCfg.CredentialsSource() |
| 93 | + |
| 94 | + // The fake discoverer returns the upstream's full URL as modules.v1, so the |
| 95 | + // proxy targets the httptest server (HTTP, not HTTPS) without DNS lookups. |
| 96 | + discoverer := &fakeDiscoverer{modulesV1: upstream.URL + "/v1/modules/"} |
| 97 | + |
| 98 | + cacheToken := fmt.Sprintf("%s:%s", providercache.APIKeyAuth, uuid.New().String()) |
| 99 | + |
| 100 | + providerCacheDir := helpers.TmpDirWOSymlinks(t) |
| 101 | + pluginCacheDir := helpers.TmpDirWOSymlinks(t) |
| 102 | + |
| 103 | + l := logger.CreateLogger() |
| 104 | + providerService := services.NewProviderService(providerCacheDir, pluginCacheDir, nil, l) |
| 105 | + proxyProviderHandler := handlers.NewProxyProviderHandler(l, credsSource) |
| 106 | + proxyModuleHandler := handlers.NewProxyModuleHandler(l, credsSource, discoverer) |
| 107 | + |
| 108 | + server := cache.NewServer( |
| 109 | + cache.WithToken(cacheToken), |
| 110 | + cache.WithProviderService(providerService), |
| 111 | + cache.WithProxyProviderHandler(proxyProviderHandler), |
| 112 | + cache.WithProxyModuleHandler(proxyModuleHandler), |
| 113 | + cache.WithCacheProviderHTTPStatusCode(providercache.CacheProviderHTTPStatusCode), |
| 114 | + cache.WithLogger(l), |
| 115 | + ) |
| 116 | + |
| 117 | + ctx, cancel := context.WithCancel(t.Context()) |
| 118 | + defer cancel() |
| 119 | + |
| 120 | + ln, err := server.Listen(ctx) |
| 121 | + require.NoError(t, err) |
| 122 | + |
| 123 | + t.Cleanup(func() { |
| 124 | + if err := ln.Close(); err != nil && !errors.Is(err, net.ErrClosed) { |
| 125 | + t.Errorf("listener close failed: %v", err) |
| 126 | + } |
| 127 | + }) |
| 128 | + |
| 129 | + g, gctx := errgroup.WithContext(ctx) |
| 130 | + g.Go(func() error { return server.Run(gctx, ln) }) |
| 131 | + |
| 132 | + // Build the same URL OpenTofu/Terraform would hit via the host block: |
| 133 | + // <cache server>/v1/modules/<cache_request_id>/<registry>/<module path> |
| 134 | + moduleURL := server.ModuleController.URL() |
| 135 | + moduleURL.Path += "/" + uuid.New().String() + "/" + registryName + "/private/lambda/aws/versions" |
| 136 | + |
| 137 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, moduleURL.String(), nil) |
| 138 | + require.NoError(t, err) |
| 139 | + // OpenTofu sends the host block's TF_TOKEN_<host> value, which Terragrunt has |
| 140 | + // rewritten to the cache server's API key. The cache server must NOT forward |
| 141 | + // this token upstream; it must look up the user's real token instead. |
| 142 | + req.Header.Set("Authorization", "Bearer "+cacheToken) |
| 143 | + |
| 144 | + resp, err := http.DefaultClient.Do(req) |
| 145 | + require.NoError(t, err) |
| 146 | + |
| 147 | + body, err := io.ReadAll(resp.Body) |
| 148 | + require.NoError(t, resp.Body.Close()) |
| 149 | + require.NoError(t, err) |
| 150 | + |
| 151 | + assert.Equal(t, http.StatusOK, resp.StatusCode, "expected upstream success; body=%s", string(body)) |
| 152 | + assert.JSONEq(t, versionsBody, string(body)) |
| 153 | + |
| 154 | + assert.Equal(t, int32(1), upstreamHits.Load(), "upstream registry should have been hit exactly once") |
| 155 | + assert.Equal(t, int32(0), upstreamReject.Load(), "upstream registry should not have rejected the request") |
| 156 | + assert.Equal(t, "Bearer "+realUserToken, upstreamAuth.Load(), |
| 157 | + "cache server must forward the user's real upstream credentials, not its own API key") |
| 158 | + |
| 159 | + cancel() |
| 160 | + require.NoError(t, g.Wait()) |
| 161 | +} |
0 commit comments