Make a HTTP request to set a header value in the Caddyfile

1. Output of caddy version

2.5.1 (Docker image: caddy:2.5.1-alpine)

2. How I run Caddy:

In Docker using Dockerfile:

FROM caddy:2.5.1-alpine

COPY ["./caddy/Caddyfile", "/etc/caddy/Caddyfile"]

a. System environment:

Docker

b. Command:

Default CMD for Docker image:

 CMD ["caddy" "run" "--config" "/etc/caddy/Caddyfile" "--adapter" "caddyfile"]

c. Service/unit/compose file:

N/A - Deployed using Cloud Run in GCP.

d. My complete Caddy config:

{
	http_port {$PORT}
	auto_https off
}

:{$PORT} {
	@0-1 header API-Version 0.1
	@missing-header header !API-Version

	redir @0-1 https://v0-1---{$API_ENDPOINT}{uri}
	redir @missing-header https://v0-1---{$API_ENDPOINT}{uri}
	respond * "Invalid API-Version" 400
}

3. The problem I’m having:

The environemnt variable $API_ENDPOINT is the HTTP endpoint of another Cloud Run instance in Google Cloud.

As the Caddy container is running in Cloud Run the GCP documentation on service to service configuration says that an authentication header must be set when making requests - and this header must be an authentication token. The token can be obtained (when running in GCP) by making a HTTP request to the GCP metadata server. An example using CURL:

curl "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=[AUDIENCE]" \
     -H "Metadata-Flavor: Google"

Is it possible to dynamically make a HTTP request to get this token and set the Authentication header in the Caddyfile? I have tried (and succeeded) in making this request in the background in a loop and reading it in as an environment variable in the Caddyfile, but I’m wondering if its possible to do this from within Caddy itself?

4. Error messages and/or full log output:

N/A

5. What I already tried:

N/A

6. Links to relevant resources:

N/A

Please upgrade to v2.5.2 (it’ll be necessary for handle_response to work properly)

Yeah I think so, with reverse_proxy to make the request then use handle_response + request_header to update the original request’s headers.

That’s essentially how the forward_auth directive works, but I’m not sure if that’s exactly the right pattern for what you’re trying to do :thinking:

2 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.