|
1 | 1 | module vweb |
2 | 2 |
|
3 | 3 | import compress.gzip |
| 4 | +import net.http |
4 | 5 |
|
5 | 6 | pub type MiddlewareHandler[T] = fn (mut T) bool |
6 | 7 |
|
@@ -173,3 +174,149 @@ pub fn decode_gzip[T]() MiddlewareOptions[T] { |
173 | 174 | interface HasBeforeRequest { |
174 | 175 | before_request() |
175 | 176 | } |
| 177 | + |
| 178 | +pub const cors_safelisted_response_headers = [http.CommonHeader.cache_control, .content_language, |
| 179 | + .content_length, .content_type, .expires, .last_modified, .pragma].map(it.str()) |
| 180 | + |
| 181 | +// CorsOptions is used to set CORS response headers. |
| 182 | +// See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#the_http_response_headers |
| 183 | +@[params] |
| 184 | +pub struct CorsOptions { |
| 185 | +pub: |
| 186 | + // from which origin(s) can cross-origin requests be made; `Access-Control-Allow-Origin` |
| 187 | + origins []string @[required] |
| 188 | + // indicate whether the server allows credentials, e.g. cookies, in cross-origin requests. |
| 189 | + // ;`Access-Control-Allow-Credentials` |
| 190 | + allow_credentials bool |
| 191 | + // allowed HTTP headers for a cross-origin request; `Access-Control-Allow-Headers` |
| 192 | + allowed_headers []string = ['*'] |
| 193 | + // allowed HTTP methods for a cross-origin request; `Access-Control-Allow-Methods` |
| 194 | + allowed_methods []http.Method |
| 195 | + // indicate if clients are able to access other headers than the "CORS-safelisted" |
| 196 | + // response headers; `Access-Control-Expose-Headers` |
| 197 | + expose_headers []string |
| 198 | + // how long the results of a preflight requets can be cached, value is in seconds |
| 199 | + // ; `Access-Control-Max-Age` |
| 200 | + max_age ?int |
| 201 | +} |
| 202 | + |
| 203 | +// set_headers adds the CORS headers on the response |
| 204 | +pub fn (options &CorsOptions) set_headers(mut ctx Context) { |
| 205 | + // A browser will reject a CORS request when the Access-Control-Allow-Origin header |
| 206 | + // is not present. By not setting the CORS headers when an invalid origin is supplied |
| 207 | + // we force the browser to reject the preflight and the actual request. |
| 208 | + origin := ctx.req.header.get(.origin) or { return } |
| 209 | + if options.origins != ['*'] && origin !in options.origins { |
| 210 | + return |
| 211 | + } |
| 212 | + |
| 213 | + ctx.set_header(.access_control_allow_origin, origin) |
| 214 | + ctx.set_header(.vary, 'Origin, Access-Control-Request-Headers') |
| 215 | + |
| 216 | + // dont' set the value of `Access-Control-Allow-Credentials` to 'false', but |
| 217 | + // omit the header if the value is `false` |
| 218 | + if options.allow_credentials { |
| 219 | + ctx.set_header(.access_control_allow_credentials, 'true') |
| 220 | + } |
| 221 | + |
| 222 | + if options.allowed_headers.len > 0 { |
| 223 | + ctx.set_header(.access_control_allow_headers, options.allowed_headers.join(',')) |
| 224 | + } else if _ := ctx.req.header.get(.access_control_request_headers) { |
| 225 | + // a server must respond with `Access-Control-Allow-Headers` if |
| 226 | + // `Access-Control-Request-Headers` is present in a preflight request |
| 227 | + ctx.set_header(.access_control_allow_headers, vweb.cors_safelisted_response_headers.join(',')) |
| 228 | + } |
| 229 | + |
| 230 | + if options.allowed_methods.len > 0 { |
| 231 | + method_str := options.allowed_methods.str().trim('[]') |
| 232 | + ctx.set_header(.access_control_allow_methods, method_str) |
| 233 | + } |
| 234 | + |
| 235 | + if options.expose_headers.len > 0 { |
| 236 | + ctx.set_header(.access_control_expose_headers, options.expose_headers.join(',')) |
| 237 | + } |
| 238 | + |
| 239 | + if max_age := options.max_age { |
| 240 | + ctx.set_header(.access_control_max_age, max_age.str()) |
| 241 | + } |
| 242 | +} |
| 243 | + |
| 244 | +// validate_request checks if a cross-origin request is made and verifies the CORS |
| 245 | +// headers. If a cross-origin request is invalid this method will send a response |
| 246 | +// using `ctx`. |
| 247 | +pub fn (options &CorsOptions) validate_request(mut ctx Context) bool { |
| 248 | + origin := ctx.req.header.get(.origin) or { return true } |
| 249 | + if options.origins != ['*'] && origin !in options.origins { |
| 250 | + ctx.res.set_status(.forbidden) |
| 251 | + ctx.text('invalid CORS origin') |
| 252 | + |
| 253 | + $if vweb_trace_cors ? { |
| 254 | + eprintln('[vweb]: rejected CORS request from "${origin}". Reason: invalid origin') |
| 255 | + } |
| 256 | + return false |
| 257 | + } |
| 258 | + |
| 259 | + ctx.set_header(.access_control_allow_origin, origin) |
| 260 | + ctx.set_header(.vary, 'Origin, Access-Control-Request-Headers') |
| 261 | + |
| 262 | + // validate request method |
| 263 | + if ctx.req.method !in options.allowed_methods { |
| 264 | + ctx.res.set_status(.method_not_allowed) |
| 265 | + ctx.text('${ctx.req.method} requests are not allowed') |
| 266 | + |
| 267 | + $if vweb_trace_cors ? { |
| 268 | + eprintln('[vweb]: rejected CORS request from "${origin}". Reason: invalid request method: ${ctx.req.method}') |
| 269 | + } |
| 270 | + return false |
| 271 | + } |
| 272 | + |
| 273 | + if options.allowed_headers.len > 0 && options.allowed_headers != ['*'] { |
| 274 | + // validate request headers |
| 275 | + for header in ctx.req.header.keys() { |
| 276 | + if header !in options.allowed_headers { |
| 277 | + ctx.res.set_status(.forbidden) |
| 278 | + ctx.text('invalid Header "${header}"') |
| 279 | + |
| 280 | + $if vweb_trace_cors ? { |
| 281 | + eprintln('[vweb]: rejected CORS request from "${origin}". Reason: invalid header "${header}"') |
| 282 | + } |
| 283 | + return false |
| 284 | + } |
| 285 | + } |
| 286 | + } |
| 287 | + |
| 288 | + $if vweb_trace_cors ? { |
| 289 | + eprintln('[vweb]: received CORS request from "${origin}": HTTP ${ctx.req.method} ${ctx.req.url}') |
| 290 | + } |
| 291 | + |
| 292 | + return true |
| 293 | +} |
| 294 | + |
| 295 | +// cors handles cross-origin requests by adding Access-Control-* headers to a |
| 296 | +// preflight request and validating the headers of a cross-origin request. |
| 297 | +// Example: |
| 298 | +// ```v |
| 299 | +// app.use(vweb.cors[Context](vweb.CorsOptions{ |
| 300 | +// origin: '*' |
| 301 | +// allowed_methods: [.get, .head, .patch, .put, .post, .delete] |
| 302 | +// })) |
| 303 | +// ``` |
| 304 | +pub fn cors[T](options CorsOptions) MiddlewareOptions[T] { |
| 305 | + return MiddlewareOptions[T]{ |
| 306 | + handler: fn [options] [T](mut ctx T) bool { |
| 307 | + if ctx.req.method == .options { |
| 308 | + // preflight request |
| 309 | + options.set_headers(mut ctx.Context) |
| 310 | + ctx.text('ok') |
| 311 | + return false |
| 312 | + } else { |
| 313 | + // check if there is a cross-origin request |
| 314 | + if options.validate_request(mut ctx.Context) == false { |
| 315 | + return false |
| 316 | + } |
| 317 | + // no cross-origin request / valid cross-origin request |
| 318 | + return true |
| 319 | + } |
| 320 | + } |
| 321 | + } |
| 322 | +} |
0 commit comments