Skip to content

feat: Add support for optional follow_redirects #526

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/data-sources/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ resource "null_resource" "example" {
- `ca_cert_pem` (String) Certificate Authority (CA) in [PEM (RFC 1421)](https://datatracker.ietf.org/doc/html/rfc1421) format.
- `client_cert_pem` (String) Client certificate in [PEM (RFC 1421)](https://datatracker.ietf.org/doc/html/rfc1421) format.
- `client_key_pem` (String) Client key in [PEM (RFC 1421)](https://datatracker.ietf.org/doc/html/rfc1421) format.
- `follow_redirects` (Boolean) If false, do not follow HTTP redirects. Defaults to true.
- `insecure` (Boolean) Disables verification of the server's certificate chain and hostname. Defaults to `false`
- `method` (String) The HTTP Method for the request. Allowed methods are a subset of methods defined in [RFC7231](https://datatracker.ietf.org/doc/html/rfc7231#section-4.3) namely, `GET`, `HEAD`, and `POST`. `POST` support is only intended for read-only URLs, such as submitting a search.
- `request_body` (String) The request body as a string.
Expand Down
13 changes: 13 additions & 0 deletions internal/provider/data_source_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@ a 5xx-range (except 501) status code is received. For further details see
Description: `The HTTP response status code.`,
Computed: true,
},

"follow_redirects": schema.BoolAttribute{
Description: "If false, do not follow HTTP redirects. Defaults to true.",
Optional: true,
},
},

Blocks: map[string]schema.Block{
Expand Down Expand Up @@ -295,6 +300,13 @@ func (d *httpDataSource) Read(ctx context.Context, req datasource.ReadRequest, r
retryClient := retryablehttp.NewClient()
retryClient.HTTPClient.Transport = clonedTr

// Configure no-follow behavior when follow_redirects is explicitly false
if !model.FollowRedirects.IsNull() && !model.FollowRedirects.ValueBool() {
retryClient.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}

var timeout time.Duration

if model.RequestTimeout.ValueInt64() > 0 {
Expand Down Expand Up @@ -437,6 +449,7 @@ type modelV0 struct {
Body types.String `tfsdk:"body"`
ResponseBodyBase64 types.String `tfsdk:"response_body_base64"`
StatusCode types.Int64 `tfsdk:"status_code"`
FollowRedirects types.Bool `tfsdk:"follow_redirects"`
}

type retryModel struct {
Expand Down
46 changes: 46 additions & 0 deletions internal/provider/data_source_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1020,6 +1020,52 @@ func TestDataSource_ResponseBodyBinary(t *testing.T) {
})
}

// TestDataSource_FollowRedirects verifies that the follow_redirects flag controls redirect behavior.
func TestDataSource_FollowRedirects(t *testing.T) {
// Target server returns 200 OK
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("OK"))
}))
defer target.Close()

// Redirect server sends 302 to target
redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusFound)
}))
defer redirect.Close()

resource.UnitTest(t, resource.TestCase{
ProtoV5ProviderFactories: protoV5ProviderFactories(),
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(`
data "http" "http_test" {
url = %q
follow_redirects = false
}
`, redirect.URL),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.http.http_test", "status_code", fmt.Sprintf("%d", http.StatusFound)),
resource.TestCheckResourceAttr("data.http.http_test", "response_headers.Location", target.URL),
),
},
{
Config: fmt.Sprintf(`
data "http" "http_test" {
url = %q
}
`, redirect.URL),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("data.http.http_test", "status_code", fmt.Sprintf("%d", http.StatusOK)),
resource.TestCheckResourceAttr("data.http.http_test", "response_body", "OK"),
),
},
},
})
}

func checkServerAndProxyRequestCount(proxyRequestCount, serverRequestCount *int) resource.TestCheckFunc {
return func(_ *terraform.State) error {
if *proxyRequestCount != *serverRequestCount {
Expand Down