-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathdata_source_http.go
More file actions
218 lines (180 loc) · 5.88 KB
/
data_source_http.go
File metadata and controls
218 lines (180 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package provider
import (
"context"
"fmt"
"io/ioutil"
"mime"
"net/http"
"regexp"
"strings"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var _ tfsdk.DataSourceType = (*httpDataSourceType)(nil)
type httpDataSourceType struct{}
func (d *httpDataSourceType) GetSchema(context.Context) (tfsdk.Schema, diag.Diagnostics) {
return tfsdk.Schema{
Description: `
The ` + "`http`" + ` data source makes an HTTP GET request to the given URL and exports
information about the response.
The given URL may be either an ` + "`http`" + ` or ` + "`https`" + ` URL. At present this resource
can only retrieve data from URLs that respond with ` + "`text/*`" + ` or
` + "`application/json`" + ` content types, and expects the result to be UTF-8 encoded
regardless of the returned content type header.
~> **Important** Although ` + "`https`" + ` URLs can be used, there is currently no
mechanism to authenticate the remote server except for general verification of
the server certificate's chain of trust. Data retrieved from servers not under
your control should be treated as untrustworthy.`,
Attributes: map[string]tfsdk.Attribute{
"url": {
Description: "The URL for the request. Supported schemes are `http` and `https`.",
Type: types.StringType,
Required: true,
},
"request_headers": {
Description: "A map of request header field names and values.",
Type: types.MapType{
ElemType: types.StringType,
},
Optional: true,
},
"response_body": {
Description: "The response body returned as a string.",
Type: types.StringType,
Computed: true,
},
"response_headers": {
Description: `A map of response header field names and values.` +
` Duplicate headers are concatenated according to [RFC2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2).`,
Type: types.MapType{
ElemType: types.StringType,
},
Computed: true,
},
"status_code": {
Description: `The HTTP response status code.`,
Type: types.Int64Type,
Computed: true,
},
"id": {
Description: "The ID of this resource.",
Type: types.StringType,
Computed: true,
},
},
}, nil
}
func (d *httpDataSourceType) NewDataSource(_ context.Context, p tfsdk.Provider) (tfsdk.DataSource, diag.Diagnostics) {
return &httpDataSource{
p: p.(*provider),
}, nil
}
var _ tfsdk.DataSource = (*httpDataSource)(nil)
type httpDataSource struct {
p *provider
}
func (d *httpDataSource) Read(ctx context.Context, req tfsdk.ReadDataSourceRequest, resp *tfsdk.ReadDataSourceResponse) {
var model modelV0
diags := req.Config.Get(ctx, &model)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
url := model.URL.Value
headers := model.RequestHeaders
client := &http.Client{
Transport: &http.Transport{
Proxy: d.p.proxyForRequestFunc(ctx),
},
}
request, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
resp.Diagnostics.AddError(
"Error creating request",
fmt.Sprintf("Error creating request: %s", err),
)
return
}
for name, value := range headers.Elems {
var header string
diags = tfsdk.ValueAs(ctx, value, &header)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
request.Header.Set(name, header)
}
response, err := client.Do(request)
if err != nil {
resp.Diagnostics.AddError(
"Error making request",
fmt.Sprintf("Error making request: %s", err),
)
return
}
defer response.Body.Close()
contentType := response.Header.Get("Content-Type")
if !isContentTypeText(contentType) {
resp.Diagnostics.AddWarning(
fmt.Sprintf("Content-Type is not recognized as a text type, got %q", contentType),
"If the content is binary data, Terraform may not properly handle the contents of the response.",
)
}
bytes, err := ioutil.ReadAll(response.Body)
if err != nil {
resp.Diagnostics.AddError(
"Error reading response body",
fmt.Sprintf("Error reading response body: %s", err),
)
return
}
responseBody := string(bytes)
responseHeaders := make(map[string]string)
for k, v := range response.Header {
// Concatenate according to RFC2616
// cf. https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
responseHeaders[k] = strings.Join(v, ", ")
}
respHeadersState := types.Map{}
diags = tfsdk.ValueFrom(ctx, responseHeaders, types.Map{ElemType: types.StringType}.Type(ctx), &respHeadersState)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
model.ID = types.String{Value: url}
model.ResponseHeaders = respHeadersState
model.ResponseBody = types.String{Value: responseBody}
model.StatusCode = types.Int64{Value: int64(response.StatusCode)}
diags = resp.State.Set(ctx, model)
resp.Diagnostics.Append(diags...)
}
// This is to prevent potential issues w/ binary files
// and generally unprintable characters
// See https://github.com/hashicorp/terraform/pull/3858#issuecomment-156856738
func isContentTypeText(contentType string) bool {
parsedType, params, err := mime.ParseMediaType(contentType)
if err != nil {
return false
}
allowedContentTypes := []*regexp.Regexp{
regexp.MustCompile("^text/.+"),
regexp.MustCompile("^application/json$"),
regexp.MustCompile(`^application/samlmetadata\+xml`),
}
for _, r := range allowedContentTypes {
if r.MatchString(parsedType) {
charset := strings.ToLower(params["charset"])
return charset == "" || charset == "utf-8" || charset == "us-ascii"
}
}
return false
}
type modelV0 struct {
ID types.String `tfsdk:"id"`
URL types.String `tfsdk:"url"`
RequestHeaders types.Map `tfsdk:"request_headers"`
ResponseHeaders types.Map `tfsdk:"response_headers"`
ResponseBody types.String `tfsdk:"response_body"`
StatusCode types.Int64 `tfsdk:"status_code"`
}