mirror of
https://github.com/caddyserver/caddy.git
synced 2026-05-26 16:52:40 -04:00
Compare commits
385 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d26cd24a11 | |||
| 8c803b503c | |||
| 7d483ff3ef | |||
| 02b8640e44 | |||
| d395633749 | |||
| 4715bbfd64 | |||
| c6f2979986 | |||
| a211c656f1 | |||
| 48ce47f1d4 | |||
| ef4e0224a8 | |||
| c8a76d003f | |||
| dd5decabe7 | |||
| d7564d632f | |||
| 88fd5f3491 | |||
| 2ae58ac13e | |||
| 01be1b54a8 | |||
| 41f5dd56e1 | |||
| 16724842d9 | |||
| 792f1c7ed7 | |||
| c8adb1b553 | |||
| 9b4acc2449 | |||
| f3aead0e4d | |||
| 571f88d86f | |||
| 0e829bc418 | |||
| 4b1a9b6cc1 | |||
| 1a345b4fa6 | |||
| 22c98ea165 | |||
| 2faeac0a10 | |||
| 9dda8fbf84 | |||
| ff67b97126 | |||
| 5b44d6cea8 | |||
| 6ab9fb6f74 | |||
| f4bf4e0097 | |||
| 21f9c20a04 | |||
| 2d12fb7ac6 | |||
| 91e62db666 | |||
| c050a37e1c | |||
| 5c47c2f147 | |||
| ffd28be90a | |||
| 141c785420 | |||
| dcbf38d0b3 | |||
| 2028da4e74 | |||
| 4ade967005 | |||
| 8af646730b | |||
| 098897bdea | |||
| 8ccfedf2bb | |||
| 2bb2ecc549 | |||
| 54a0c8f948 | |||
| 043fe41ab8 | |||
| 9ddb78fadc | |||
| 3a48b03369 | |||
| 7cf8376e63 | |||
| 21af88fefc | |||
| 52bad45181 | |||
| b85b6c6469 | |||
| 59cbb2c83a | |||
| a8b0dfa8da | |||
| b198678174 | |||
| 840094ac65 | |||
| 976469ca0d | |||
| 9cc26ee7bf | |||
| 3579815a6c | |||
| 61fe152c60 | |||
| 3afa02ba4e | |||
| 806f5b1117 | |||
| b2492f8567 | |||
| 07c863637d | |||
| dc2a5d5c52 | |||
| 4943a4fc52 | |||
| 630c62b313 | |||
| 9338741ca7 | |||
| 88c7e53da5 | |||
| 4ef360745d | |||
| 7142d7c1e4 | |||
| c3fb5f4d3f | |||
| 15d986e1c9 | |||
| f350e001b6 | |||
| 0287009ee5 | |||
| f8861ca16b | |||
| c2ccf8690f | |||
| 99dcdf7e42 | |||
| fab6375a8b | |||
| aca4002fd8 | |||
| 8e0d3e1ec5 | |||
| d85cc2ec10 | |||
| 04fb9fe87f | |||
| 0bc27e5fb1 | |||
| 9be4f194e0 | |||
| a10117f8bd | |||
| 101d3e7407 | |||
| 3f1add6c9f | |||
| 5db2f81695 | |||
| 243351b2b1 | |||
| 198f4385d2 | |||
| e7ecc7ede2 | |||
| 7088605cc1 | |||
| 15faeacb60 | |||
| f8a2c60297 | |||
| 01308b4bae | |||
| b7280e6949 | |||
| a63767d3f8 | |||
| 40c582ce82 | |||
| a52917a37d | |||
| e6f46c8d78 | |||
| f6d2c293e7 | |||
| 2ce5c65269 | |||
| 61917c3443 | |||
| 224316eaec | |||
| 5f6758dab5 | |||
| a6a45ff6c5 | |||
| 73e094e1dd | |||
| d79c0f0dec | |||
| db3e19b7b5 | |||
| 1fc151faec | |||
| 9ba999141b | |||
| f98f449f05 | |||
| e66040a6f0 | |||
| 44860482d2 | |||
| 4c90f1427f | |||
| fb63e2e40c | |||
| 583c585c81 | |||
| 4356635d12 | |||
| 4af38e5ac8 | |||
| 399186abfc | |||
| 6dce4934f0 | |||
| 874d0ce822 | |||
| abdf1ae15c | |||
| d7e3a1974b | |||
| e60148ecc3 | |||
| 0b5720faa5 | |||
| dd203ad41f | |||
| b2b29dcd49 | |||
| c97292b255 | |||
| b52271061d | |||
| d05d715a00 | |||
| 8d7ac18402 | |||
| 7e2510ef43 | |||
| feeb6af403 | |||
| d129ae6aec | |||
| 87c7127c28 | |||
| 2fc620d38d | |||
| a46ff50a1c | |||
| cabb5d71c4 | |||
| ba5811467a | |||
| 1b9042bcdd | |||
| 4d6370bf92 | |||
| c6eb186064 | |||
| 76c4cf5a56 | |||
| 797973944f | |||
| 6d97d8d87b | |||
| d404005339 | |||
| 868af6a062 | |||
| d2668cdbb0 | |||
| 6a02999054 | |||
| 9f97df2275 | |||
| d93e027e01 | |||
| 613d544a47 | |||
| 726a9a8fde | |||
| d00824f4a6 | |||
| 8f87c5d993 | |||
| c6673ad4d8 | |||
| 9ab09433de | |||
| 3067074d9c | |||
| 3efda6fb3a | |||
| 9cd472c031 | |||
| e0daa39cd3 | |||
| 70953e873a | |||
| eafc875ea9 | |||
| 03e0a010d1 | |||
| 3609a4af75 | |||
| 26748d06b4 | |||
| b40cacf5ce | |||
| 81413caea2 | |||
| dc9dd2e4b3 | |||
| 567d96c624 | |||
| 5d8b45c9fb | |||
| 0b381eb766 | |||
| 83ef61de10 | |||
| e1f4b83ffa | |||
| 185ed6fe7c | |||
| 4a0492f3e1 | |||
| 654a3bb090 | |||
| f4840cfeb8 | |||
| a4a64a6f6e | |||
| 88d65967b5 | |||
| 1c4a807667 | |||
| 45132c5b24 | |||
| 1217449609 | |||
| e0bf179c1a | |||
| 7b48ce0e7e | |||
| 924010cd3d | |||
| 74949fb091 | |||
| ddb1d2c2b1 | |||
| 7f227b9d39 | |||
| 0dd0487eba | |||
| db9d167354 | |||
| 29f57faa86 | |||
| 0c01547037 | |||
| e7336cc3bf | |||
| 97a56d860a | |||
| d13258423d | |||
| 32f7dd44ae | |||
| 63d597c09d | |||
| e65b97f55b | |||
| a9768d2fde | |||
| 52822a41cb | |||
| 5b5f8feaf7 | |||
| c93e30454f | |||
| 1bd598e90c | |||
| e698ec5139 | |||
| c27425ef5d | |||
| 258d906140 | |||
| 69290d232d | |||
| 277472d081 | |||
| 5a4374bea0 | |||
| 0d44e3ecba | |||
| 2a78c9c5e4 | |||
| 01d5568b20 | |||
| 1f4a6fa7e7 | |||
| 5ed8689629 | |||
| 3ae07a73dc | |||
| e473ae6803 | |||
| 72ce78d9af | |||
| 8f8204708a | |||
| 46c5db92da | |||
| de4959fe7b | |||
| 03f703a00e | |||
| 931656bd68 | |||
| da6a569e85 | |||
| 4512be49a9 | |||
| f8143a3af1 | |||
| 8bbf8ec629 | |||
| 4284e39a17 | |||
| 53f7035299 | |||
| b893c8c5f8 | |||
| 127788807f | |||
| 2c48dda109 | |||
| 30d63648f5 | |||
| 21744b6c4c | |||
| f9e11158bc | |||
| 91ec75441a | |||
| e7a534d0a3 | |||
| c78ebb3d6a | |||
| a6d9f9be5b | |||
| 2348ac897a | |||
| d3f23a8eeb | |||
| 60abd72c7a | |||
| b8f729b88f | |||
| e1aa862e6a | |||
| 8c2a72ad07 | |||
| bde46211e3 | |||
| bc1e63198d | |||
| feb07a7b59 | |||
| a7479302fc | |||
| 223f314331 | |||
| 1919c08ecc | |||
| 57c5b921a4 | |||
| e1b9a9d7b0 | |||
| 697cc593a1 | |||
| 2fe69a828f | |||
| c369df5c37 | |||
| 7c48b5fdbb | |||
| e965b111cd | |||
| b9c40e7111 | |||
| f5344f8cad | |||
| 750d0b8331 | |||
| 54823f52bc | |||
| ed7e3c906a | |||
| c0273f1f04 | |||
| dba556fe4b | |||
| d9aded016c | |||
| 4181c79a81 | |||
| 5e2f1b5ced | |||
| f3e849e49f | |||
| f658fd05ac | |||
| cc0c0cf03e | |||
| 80acf1bf23 | |||
| c839a98ff5 | |||
| b359ca565c | |||
| c2d889f85e | |||
| cb86319bd5 | |||
| ed41c924cf | |||
| d9ff7b1872 | |||
| 76611fa150 | |||
| 8a50f191bf | |||
| 4f3f6e35e8 | |||
| 787f6b257f | |||
| b568a10dd4 | |||
| 8f9ffc587e | |||
| f976c84d9e | |||
| 1bf72db6ff | |||
| d54dcf1598 | |||
| 3248e4c89f | |||
| da7d8cb26d | |||
| 387545a895 | |||
| b49ec05161 | |||
| b16aba5c27 | |||
| 362f33daae | |||
| 3d7d60f7cf | |||
| dc12bd9743 | |||
| 56c6b3f673 | |||
| cbbd1df904 | |||
| 7d919af01b | |||
| 4a09cf0dc0 | |||
| b24ae63ea6 | |||
| 4173e2c77a | |||
| 18f34290d2 | |||
| 22eecdb90c | |||
| 4de2c1c65e | |||
| 878d491834 | |||
| 96f638eaad | |||
| 7e52db8280 | |||
| 3b3d678714 | |||
| ee358550e4 | |||
| 3f55efcfde | |||
| f71d779009 | |||
| d949caf459 | |||
| ac0ad4da84 | |||
| 4c10a05431 | |||
| fe2a02bf7a | |||
| 9fc55a9792 | |||
| 4e8245df0b | |||
| ac1f20b9e4 | |||
| 174c19a953 | |||
| c8559c4485 | |||
| 24b0ecc310 | |||
| 7c82e265da | |||
| 0900844c81 | |||
| 7984e6f6fd | |||
| d70608b656 | |||
| 1f60328e17 | |||
| 0e204b730a | |||
| fae195ac7e | |||
| 130f6d1f83 | |||
| 289934f3d1 | |||
| 3a3182fba3 | |||
| e8b8d4a8cd | |||
| a8586b05aa | |||
| 05dbe1c171 | |||
| 33d8d2c6b5 | |||
| 9c419f1e1a | |||
| b245ecd325 | |||
| 2a6859a5e4 | |||
| df99502977 | |||
| e0aaefab80 | |||
| fa5a579b60 | |||
| 88b4fbf244 | |||
| 5653c36bc2 | |||
| 4feac4d83c | |||
| 82c356f254 | |||
| 1405683c2b | |||
| 89c407aa34 | |||
| 58ab3a01a0 | |||
| a306c5f769 | |||
| 1e0dea59ef | |||
| 2cac3c5491 | |||
| f2ab7099db | |||
| 50cea4e263 | |||
| 1b73e3862d | |||
| c46ec3b500 | |||
| ed8bb13c5d | |||
| b7e472d548 | |||
| 7103ea096f | |||
| 888c6d7e93 | |||
| b377208ede | |||
| 4776f62caa | |||
| 38a7b6b3d0 | |||
| 84d5e1c5d6 | |||
| 288216e1fb | |||
| 10053f7570 | |||
| 0a6d3333b2 | |||
| 568fd2b286 | |||
| f11c3c9f5a | |||
| 936ee918ee | |||
| d6f86cccf5 | |||
| 2d7d806fcf | |||
| d8135505d3 | |||
| 11166889c5 | |||
| 080db93817 | |||
| a8492c064d | |||
| 6cdcc2a782 | |||
| fbb0ecfa32 | |||
| 5b9c850ab3 | |||
| b32f265eca | |||
| 431adc0980 |
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
[*]
|
[*]
|
||||||
end_of_line = lf
|
end_of_line = lf
|
||||||
|
|
||||||
[caddytest/integration/caddyfile_adapt/*.txt]
|
[caddytest/integration/caddyfile_adapt/*.caddyfiletest]
|
||||||
indent_style = tab
|
indent_style = tab
|
||||||
@@ -25,7 +25,7 @@ Other menu items:
|
|||||||
|
|
||||||
You can have a huge impact on the project by helping with its code. To contribute code to Caddy, first submit or comment in an issue to discuss your contribution, then open a [pull request](https://github.com/caddyserver/caddy/pulls) (PR). If you're new to our community, that's okay: **we gladly welcome pull requests from anyone, regardless of your native language or coding experience.** You can get familiar with Caddy's code base by using [code search at Sourcegraph](https://sourcegraph.com/github.com/caddyserver/caddy).
|
You can have a huge impact on the project by helping with its code. To contribute code to Caddy, first submit or comment in an issue to discuss your contribution, then open a [pull request](https://github.com/caddyserver/caddy/pulls) (PR). If you're new to our community, that's okay: **we gladly welcome pull requests from anyone, regardless of your native language or coding experience.** You can get familiar with Caddy's code base by using [code search at Sourcegraph](https://sourcegraph.com/github.com/caddyserver/caddy).
|
||||||
|
|
||||||
We hold contributions to a high standard for quality :bowtie:, so don't be surprised if we ask for revisions—even if it seems small or insignificant. Please don't take it personally. :blue_heart: If your change is on the right track, we can guide you to make it mergable.
|
We hold contributions to a high standard for quality :bowtie:, so don't be surprised if we ask for revisions—even if it seems small or insignificant. Please don't take it personally. :blue_heart: If your change is on the right track, we can guide you to make it mergeable.
|
||||||
|
|
||||||
Here are some of the expectations we have of contributors:
|
Here are some of the expectations we have of contributors:
|
||||||
|
|
||||||
|
|||||||
+74
-26
@@ -19,45 +19,49 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
os:
|
os:
|
||||||
- ubuntu-latest
|
- linux
|
||||||
- macos-latest
|
- mac
|
||||||
- windows-latest
|
- windows
|
||||||
go:
|
go:
|
||||||
- '1.20'
|
- '1.22'
|
||||||
# - '1.21'
|
- '1.23'
|
||||||
|
|
||||||
include:
|
include:
|
||||||
# Set the minimum Go patch version for the given Go minor
|
# Set the minimum Go patch version for the given Go minor
|
||||||
# Usable via ${{ matrix.GO_SEMVER }}
|
# Usable via ${{ matrix.GO_SEMVER }}
|
||||||
- go: '1.20'
|
- go: '1.22'
|
||||||
GO_SEMVER: '~1.20.6'
|
GO_SEMVER: '~1.22.3'
|
||||||
|
|
||||||
# - go: '1.21'
|
- go: '1.23'
|
||||||
# GO_SEMVER: '~1.21.0'
|
GO_SEMVER: '~1.23.0'
|
||||||
|
|
||||||
# Set some variables per OS, usable via ${{ matrix.VAR }}
|
# Set some variables per OS, usable via ${{ matrix.VAR }}
|
||||||
|
# OS_LABEL: the VM label from GitHub Actions (see https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories)
|
||||||
# CADDY_BIN_PATH: the path to the compiled Caddy binary, for artifact publishing
|
# CADDY_BIN_PATH: the path to the compiled Caddy binary, for artifact publishing
|
||||||
# SUCCESS: the typical value for $? per OS (Windows/pwsh returns 'True')
|
# SUCCESS: the typical value for $? per OS (Windows/pwsh returns 'True')
|
||||||
- os: ubuntu-latest
|
- os: linux
|
||||||
|
OS_LABEL: ubuntu-latest
|
||||||
CADDY_BIN_PATH: ./cmd/caddy/caddy
|
CADDY_BIN_PATH: ./cmd/caddy/caddy
|
||||||
SUCCESS: 0
|
SUCCESS: 0
|
||||||
|
|
||||||
- os: macos-latest
|
- os: mac
|
||||||
|
OS_LABEL: macos-14
|
||||||
CADDY_BIN_PATH: ./cmd/caddy/caddy
|
CADDY_BIN_PATH: ./cmd/caddy/caddy
|
||||||
SUCCESS: 0
|
SUCCESS: 0
|
||||||
|
|
||||||
- os: windows-latest
|
- os: windows
|
||||||
|
OS_LABEL: windows-latest
|
||||||
CADDY_BIN_PATH: ./cmd/caddy/caddy.exe
|
CADDY_BIN_PATH: ./cmd/caddy/caddy.exe
|
||||||
SUCCESS: 'True'
|
SUCCESS: 'True'
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.OS_LABEL }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Go
|
- name: Install Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.GO_SEMVER }}
|
go-version: ${{ matrix.GO_SEMVER }}
|
||||||
check-latest: true
|
check-latest: true
|
||||||
@@ -73,6 +77,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Print Go version and environment
|
- name: Print Go version and environment
|
||||||
id: vars
|
id: vars
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
printf "Using go at: $(which go)\n"
|
printf "Using go at: $(which go)\n"
|
||||||
printf "Go version: $(go version)\n"
|
printf "Go version: $(go version)\n"
|
||||||
@@ -94,13 +99,20 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
CGO_ENABLED: 0
|
CGO_ENABLED: 0
|
||||||
run: |
|
run: |
|
||||||
go build -trimpath -ldflags="-w -s" -v
|
go build -tags nobadger -trimpath -ldflags="-w -s" -v
|
||||||
|
|
||||||
|
- name: Smoke test Caddy
|
||||||
|
working-directory: ./cmd/caddy
|
||||||
|
run: |
|
||||||
|
./caddy start
|
||||||
|
./caddy stop
|
||||||
|
|
||||||
- name: Publish Build Artifact
|
- name: Publish Build Artifact
|
||||||
uses: actions/upload-artifact@v3
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: caddy_${{ runner.os }}_go${{ matrix.go }}_${{ steps.vars.outputs.short_sha }}
|
name: caddy_${{ runner.os }}_go${{ matrix.go }}_${{ steps.vars.outputs.short_sha }}
|
||||||
path: ${{ matrix.CADDY_BIN_PATH }}
|
path: ${{ matrix.CADDY_BIN_PATH }}
|
||||||
|
compression-level: 0
|
||||||
|
|
||||||
# Commented bits below were useful to allow the job to continue
|
# Commented bits below were useful to allow the job to continue
|
||||||
# even if the tests fail, so we can publish the report separately
|
# even if the tests fail, so we can publish the report separately
|
||||||
@@ -110,7 +122,7 @@ jobs:
|
|||||||
# continue-on-error: true
|
# continue-on-error: true
|
||||||
run: |
|
run: |
|
||||||
# (go test -v -coverprofile=cover-profile.out -race ./... 2>&1) > test-results/test-result.out
|
# (go test -v -coverprofile=cover-profile.out -race ./... 2>&1) > test-results/test-result.out
|
||||||
go test -v -coverprofile="cover-profile.out" -short -race ./...
|
go test -tags nobadger -v -coverprofile="cover-profile.out" -short -race ./...
|
||||||
# echo "status=$?" >> $GITHUB_OUTPUT
|
# echo "status=$?" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
# Relevant step if we reinvestigate publishing test/coverage reports
|
# Relevant step if we reinvestigate publishing test/coverage reports
|
||||||
@@ -123,7 +135,7 @@ jobs:
|
|||||||
|
|
||||||
# To return the correct result even though we set 'continue-on-error: true'
|
# To return the correct result even though we set 'continue-on-error: true'
|
||||||
# - name: Coerce correct build result
|
# - name: Coerce correct build result
|
||||||
# if: matrix.os != 'windows-latest' && steps.step_test.outputs.status != ${{ matrix.SUCCESS }}
|
# if: matrix.os != 'windows' && steps.step_test.outputs.status != ${{ matrix.SUCCESS }}
|
||||||
# run: |
|
# run: |
|
||||||
# echo "step_test ${{ steps.step_test.outputs.status }}\n"
|
# echo "step_test ${{ steps.step_test.outputs.status }}\n"
|
||||||
# exit 1
|
# exit 1
|
||||||
@@ -135,21 +147,44 @@ jobs:
|
|||||||
continue-on-error: true # August 2020: s390x VM is down due to weather and power issues
|
continue-on-error: true # August 2020: s390x VM is down due to weather and power issues
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
- name: Run Tests
|
- name: Run Tests
|
||||||
run: |
|
run: |
|
||||||
|
set +e
|
||||||
mkdir -p ~/.ssh && echo -e "${SSH_KEY//_/\\n}" > ~/.ssh/id_ecdsa && chmod og-rwx ~/.ssh/id_ecdsa
|
mkdir -p ~/.ssh && echo -e "${SSH_KEY//_/\\n}" > ~/.ssh/id_ecdsa && chmod og-rwx ~/.ssh/id_ecdsa
|
||||||
|
|
||||||
# short sha is enough?
|
# short sha is enough?
|
||||||
short_sha=$(git rev-parse --short HEAD)
|
short_sha=$(git rev-parse --short HEAD)
|
||||||
|
|
||||||
|
# To shorten the following lines
|
||||||
|
ssh_opts="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
|
||||||
|
ssh_host="$CI_USER@ci-s390x.caddyserver.com"
|
||||||
|
|
||||||
# The environment is fresh, so there's no point in keeping accepting and adding the key.
|
# The environment is fresh, so there's no point in keeping accepting and adding the key.
|
||||||
rsync -arz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress --delete --exclude '.git' . "$CI_USER"@ci-s390x.caddyserver.com:/var/tmp/"$short_sha"
|
rsync -arz -e "ssh $ssh_opts" --progress --delete --exclude '.git' . "$ssh_host":/var/tmp/"$short_sha"
|
||||||
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -t "$CI_USER"@ci-s390x.caddyserver.com "cd /var/tmp/$short_sha; go version; go env; printf "\n\n";CGO_ENABLED=0 go test -v ./..."
|
ssh $ssh_opts -t "$ssh_host" bash <<EOF
|
||||||
|
cd /var/tmp/$short_sha
|
||||||
|
go version
|
||||||
|
go env
|
||||||
|
printf "\n\n"
|
||||||
|
retries=3
|
||||||
|
exit_code=0
|
||||||
|
while ((retries > 0)); do
|
||||||
|
CGO_ENABLED=0 go test -p 1 -tags nobadger -v ./...
|
||||||
|
exit_code=$?
|
||||||
|
if ((exit_code == 0)); then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
echo "\n\nTest failed: \$exit_code, retrying..."
|
||||||
|
((retries--))
|
||||||
|
done
|
||||||
|
echo "Remote exit code: \$exit_code"
|
||||||
|
exit \$exit_code
|
||||||
|
EOF
|
||||||
test_result=$?
|
test_result=$?
|
||||||
|
|
||||||
# There's no need leaving the files around
|
# There's no need leaving the files around
|
||||||
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$CI_USER"@ci-s390x.caddyserver.com "rm -rf /var/tmp/'$short_sha'"
|
ssh $ssh_opts "$ssh_host" "rm -rf /var/tmp/'$short_sha'"
|
||||||
|
|
||||||
echo "Test exit code: $test_result"
|
echo "Test exit code: $test_result"
|
||||||
exit $test_result
|
exit $test_result
|
||||||
@@ -161,11 +196,24 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: goreleaser/goreleaser-action@v4
|
- uses: goreleaser/goreleaser-action@v6
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
args: check
|
args: check
|
||||||
|
- name: Install Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: "~1.23"
|
||||||
|
check-latest: true
|
||||||
|
- name: Install xcaddy
|
||||||
|
run: |
|
||||||
|
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
|
||||||
|
xcaddy version
|
||||||
|
- uses: goreleaser/goreleaser-action@v6
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
args: build --single-target --snapshot
|
||||||
env:
|
env:
|
||||||
TAG: ${{ steps.vars.outputs.version_tag }}
|
TAG: "master"
|
||||||
|
|||||||
@@ -11,39 +11,42 @@ on:
|
|||||||
- 2.*
|
- 2.*
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
cross-build-test:
|
build:
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
goos:
|
goos:
|
||||||
- 'android'
|
- 'aix'
|
||||||
- 'linux'
|
- 'linux'
|
||||||
- 'solaris'
|
- 'solaris'
|
||||||
- 'illumos'
|
- 'illumos'
|
||||||
- 'dragonfly'
|
- 'dragonfly'
|
||||||
- 'freebsd'
|
- 'freebsd'
|
||||||
- 'openbsd'
|
- 'openbsd'
|
||||||
- 'plan9'
|
|
||||||
- 'windows'
|
- 'windows'
|
||||||
- 'darwin'
|
- 'darwin'
|
||||||
- 'netbsd'
|
- 'netbsd'
|
||||||
go:
|
go:
|
||||||
- '1.20'
|
- '1.22'
|
||||||
|
- '1.23'
|
||||||
|
|
||||||
include:
|
include:
|
||||||
# Set the minimum Go patch version for the given Go minor
|
# Set the minimum Go patch version for the given Go minor
|
||||||
# Usable via ${{ matrix.GO_SEMVER }}
|
# Usable via ${{ matrix.GO_SEMVER }}
|
||||||
- go: '1.20'
|
- go: '1.22'
|
||||||
GO_SEMVER: '~1.20.6'
|
GO_SEMVER: '~1.22.3'
|
||||||
|
|
||||||
|
- go: '1.23'
|
||||||
|
GO_SEMVER: '~1.23.0'
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Go
|
- name: Install Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.GO_SEMVER }}
|
go-version: ${{ matrix.GO_SEMVER }}
|
||||||
check-latest: true
|
check-latest: true
|
||||||
@@ -62,12 +65,9 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
CGO_ENABLED: 0
|
CGO_ENABLED: 0
|
||||||
GOOS: ${{ matrix.goos }}
|
GOOS: ${{ matrix.goos }}
|
||||||
|
GOARCH: ${{ matrix.goos == 'aix' && 'ppc64' || 'amd64' }}
|
||||||
shell: bash
|
shell: bash
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
working-directory: ./cmd/caddy
|
working-directory: ./cmd/caddy
|
||||||
run: |
|
run: |
|
||||||
GOOS=$GOOS go build -trimpath -o caddy-"$GOOS"-amd64 2> /dev/null
|
GOOS=$GOOS GOARCH=$GOARCH go build -tags nobadger -trimpath -o caddy-"$GOOS"-$GOARCH 2> /dev/null
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "::warning ::$GOOS Build Failed"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|||||||
+30
-15
@@ -23,30 +23,45 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os:
|
os:
|
||||||
- ubuntu-latest
|
- linux
|
||||||
- macos-latest
|
- mac
|
||||||
- windows-latest
|
- windows
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
|
include:
|
||||||
|
- os: linux
|
||||||
|
OS_LABEL: ubuntu-latest
|
||||||
|
|
||||||
|
- os: mac
|
||||||
|
OS_LABEL: macos-14
|
||||||
|
|
||||||
|
- os: windows
|
||||||
|
OS_LABEL: windows-latest
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.OS_LABEL }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: '~1.20.6'
|
go-version: '~1.23'
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
# Workaround for https://github.com/golangci/golangci-lint-action/issues/135
|
|
||||||
skip-pkg-cache: true
|
|
||||||
|
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v3
|
uses: golangci/golangci-lint-action@v6
|
||||||
with:
|
with:
|
||||||
version: v1.53
|
version: latest
|
||||||
|
|
||||||
# Workaround for https://github.com/golangci/golangci-lint-action/issues/135
|
|
||||||
skip-pkg-cache: true
|
|
||||||
|
|
||||||
# Windows times out frequently after about 5m50s if we don't set a longer timeout.
|
# Windows times out frequently after about 5m50s if we don't set a longer timeout.
|
||||||
args: --timeout 10m
|
args: --timeout 10m
|
||||||
|
|
||||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||||
# only-new-issues: true
|
# only-new-issues: true
|
||||||
|
|
||||||
|
govulncheck:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: govulncheck
|
||||||
|
uses: golang/govulncheck-action@v1
|
||||||
|
with:
|
||||||
|
go-version-input: '~1.23.0'
|
||||||
|
check-latest: true
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ jobs:
|
|||||||
os:
|
os:
|
||||||
- ubuntu-latest
|
- ubuntu-latest
|
||||||
go:
|
go:
|
||||||
- '1.20'
|
- '1.23'
|
||||||
|
|
||||||
include:
|
include:
|
||||||
# Set the minimum Go patch version for the given Go minor
|
# Set the minimum Go patch version for the given Go minor
|
||||||
# Usable via ${{ matrix.GO_SEMVER }}
|
# Usable via ${{ matrix.GO_SEMVER }}
|
||||||
- go: '1.20'
|
- go: '1.23'
|
||||||
GO_SEMVER: '~1.20.6'
|
GO_SEMVER: '~1.23.0'
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
# https://github.com/sigstore/cosign/issues/1258#issuecomment-1002251233
|
# https://github.com/sigstore/cosign/issues/1258#issuecomment-1002251233
|
||||||
@@ -32,18 +32,18 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Install Go
|
- name: Install Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ matrix.GO_SEMVER }}
|
go-version: ${{ matrix.GO_SEMVER }}
|
||||||
check-latest: true
|
check-latest: true
|
||||||
|
|
||||||
# Force fetch upstream tags -- because 65 minutes
|
# Force fetch upstream tags -- because 65 minutes
|
||||||
# tl;dr: actions/checkout@v3 runs this line:
|
# tl;dr: actions/checkout@v4 runs this line:
|
||||||
# git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules --depth=1 origin +ebc278ec98bb24f2852b61fde2a9bf2e3d83818b:refs/tags/
|
# git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules --depth=1 origin +ebc278ec98bb24f2852b61fde2a9bf2e3d83818b:refs/tags/
|
||||||
# which makes its own local lightweight tag, losing all the annotations in the process. Our earlier script ran:
|
# which makes its own local lightweight tag, losing all the annotations in the process. Our earlier script ran:
|
||||||
# git fetch --prune --unshallow
|
# git fetch --prune --unshallow
|
||||||
@@ -104,9 +104,13 @@ jobs:
|
|||||||
uses: anchore/sbom-action/download-syft@main
|
uses: anchore/sbom-action/download-syft@main
|
||||||
- name: Syft version
|
- name: Syft version
|
||||||
run: syft version
|
run: syft version
|
||||||
|
- name: Install xcaddy
|
||||||
|
run: |
|
||||||
|
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
|
||||||
|
xcaddy version
|
||||||
# GoReleaser will take care of publishing those artifacts into the release
|
# GoReleaser will take care of publishing those artifacts into the release
|
||||||
- name: Run GoReleaser
|
- name: Run GoReleaser
|
||||||
uses: goreleaser/goreleaser-action@v4
|
uses: goreleaser/goreleaser-action@v6
|
||||||
with:
|
with:
|
||||||
version: latest
|
version: latest
|
||||||
args: release --clean --timeout 60m
|
args: release --clean --timeout 60m
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ jobs:
|
|||||||
|
|
||||||
# See https://github.com/peter-evans/repository-dispatch
|
# See https://github.com/peter-evans/repository-dispatch
|
||||||
- name: Trigger event on caddyserver/dist
|
- name: Trigger event on caddyserver/dist
|
||||||
uses: peter-evans/repository-dispatch@v2
|
uses: peter-evans/repository-dispatch@v3
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
|
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
|
||||||
repository: caddyserver/dist
|
repository: caddyserver/dist
|
||||||
@@ -26,7 +26,7 @@ jobs:
|
|||||||
client-payload: '{"tag": "${{ github.event.release.tag_name }}"}'
|
client-payload: '{"tag": "${{ github.event.release.tag_name }}"}'
|
||||||
|
|
||||||
- name: Trigger event on caddyserver/caddy-docker
|
- name: Trigger event on caddyserver/caddy-docker
|
||||||
uses: peter-evans/repository-dispatch@v2
|
uses: peter-evans/repository-dispatch@v3
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
|
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
|
||||||
repository: caddyserver/caddy-docker
|
repository: caddyserver/caddy-docker
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ _gitignore/
|
|||||||
Caddyfile
|
Caddyfile
|
||||||
Caddyfile.*
|
Caddyfile.*
|
||||||
!caddyfile/
|
!caddyfile/
|
||||||
|
!caddyfile.go
|
||||||
|
|
||||||
# artifacts from pprof tooling
|
# artifacts from pprof tooling
|
||||||
*.prof
|
*.prof
|
||||||
@@ -12,6 +13,7 @@ Caddyfile.*
|
|||||||
cmd/caddy/caddy
|
cmd/caddy/caddy
|
||||||
cmd/caddy/caddy.exe
|
cmd/caddy/caddy.exe
|
||||||
cmd/caddy/tmp/*.exe
|
cmd/caddy/tmp/*.exe
|
||||||
|
cmd/caddy/.env
|
||||||
|
|
||||||
# mac specific
|
# mac specific
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
+105
-22
@@ -1,36 +1,83 @@
|
|||||||
linters-settings:
|
linters-settings:
|
||||||
errcheck:
|
errcheck:
|
||||||
ignore: fmt:.*,go.uber.org/zap/zapcore:^Add.*
|
exclude-functions:
|
||||||
ignoretests: true
|
- fmt.*
|
||||||
|
- (go.uber.org/zap/zapcore.ObjectEncoder).AddObject
|
||||||
|
- (go.uber.org/zap/zapcore.ObjectEncoder).AddArray
|
||||||
|
gci:
|
||||||
|
sections:
|
||||||
|
- standard # Standard section: captures all standard packages.
|
||||||
|
- default # Default section: contains all imports that could not be matched to another section type.
|
||||||
|
- prefix(github.com/caddyserver/caddy/v2/cmd) # ensure that this is always at the top and always has a line break.
|
||||||
|
- prefix(github.com/caddyserver/caddy) # Custom section: groups all imports with the specified Prefix.
|
||||||
|
# Skip generated files.
|
||||||
|
# Default: true
|
||||||
|
skip-generated: true
|
||||||
|
# Enable custom order of sections.
|
||||||
|
# If `true`, make the section order the same as the order of `sections`.
|
||||||
|
# Default: false
|
||||||
|
custom-order: true
|
||||||
|
exhaustive:
|
||||||
|
ignore-enum-types: reflect.Kind|svc.Cmd
|
||||||
|
|
||||||
linters:
|
linters:
|
||||||
disable-all: true
|
disable-all: true
|
||||||
enable:
|
enable:
|
||||||
|
- asasalint
|
||||||
|
- asciicheck
|
||||||
|
- bidichk
|
||||||
- bodyclose
|
- bodyclose
|
||||||
|
- decorder
|
||||||
|
- dogsled
|
||||||
|
- dupl
|
||||||
|
- dupword
|
||||||
|
- durationcheck
|
||||||
- errcheck
|
- errcheck
|
||||||
|
- errname
|
||||||
|
- exhaustive
|
||||||
|
- gci
|
||||||
- gofmt
|
- gofmt
|
||||||
- goimports
|
- goimports
|
||||||
|
- gofumpt
|
||||||
- gosec
|
- gosec
|
||||||
- gosimple
|
- gosimple
|
||||||
- govet
|
- govet
|
||||||
- ineffassign
|
- ineffassign
|
||||||
|
- importas
|
||||||
- misspell
|
- misspell
|
||||||
- prealloc
|
- prealloc
|
||||||
|
- promlinter
|
||||||
|
- sloglint
|
||||||
|
- sqlclosecheck
|
||||||
- staticcheck
|
- staticcheck
|
||||||
|
- tenv
|
||||||
|
- testableexamples
|
||||||
|
- testifylint
|
||||||
|
- tparallel
|
||||||
- typecheck
|
- typecheck
|
||||||
- unconvert
|
- unconvert
|
||||||
- unused
|
- unused
|
||||||
|
- wastedassign
|
||||||
|
- whitespace
|
||||||
|
- zerologlint
|
||||||
# these are implicitly disabled:
|
# these are implicitly disabled:
|
||||||
# - asciicheck
|
# - containedctx
|
||||||
|
# - contextcheck
|
||||||
|
# - cyclop
|
||||||
# - depguard
|
# - depguard
|
||||||
# - dogsled
|
# - errchkjson
|
||||||
# - dupl
|
# - errorlint
|
||||||
# - exhaustive
|
# - exhaustruct
|
||||||
# - exportloopref
|
# - execinquery
|
||||||
|
# - exhaustruct
|
||||||
|
# - forbidigo
|
||||||
|
# - forcetypeassert
|
||||||
# - funlen
|
# - funlen
|
||||||
# - gci
|
# - ginkgolinter
|
||||||
|
# - gocheckcompilerdirectives
|
||||||
# - gochecknoglobals
|
# - gochecknoglobals
|
||||||
# - gochecknoinits
|
# - gochecknoinits
|
||||||
|
# - gochecksumtype
|
||||||
# - gocognit
|
# - gocognit
|
||||||
# - goconst
|
# - goconst
|
||||||
# - gocritic
|
# - gocritic
|
||||||
@@ -38,62 +85,98 @@ linters:
|
|||||||
# - godot
|
# - godot
|
||||||
# - godox
|
# - godox
|
||||||
# - goerr113
|
# - goerr113
|
||||||
# - gofumpt
|
|
||||||
# - goheader
|
# - goheader
|
||||||
# - golint
|
|
||||||
# - gomnd
|
# - gomnd
|
||||||
|
# - gomoddirectives
|
||||||
# - gomodguard
|
# - gomodguard
|
||||||
# - goprintffuncname
|
# - goprintffuncname
|
||||||
# - interfacer
|
# - gosmopolitan
|
||||||
|
# - grouper
|
||||||
|
# - inamedparam
|
||||||
|
# - interfacebloat
|
||||||
|
# - ireturn
|
||||||
# - lll
|
# - lll
|
||||||
# - maligned
|
# - loggercheck
|
||||||
|
# - maintidx
|
||||||
|
# - makezero
|
||||||
|
# - mirror
|
||||||
|
# - musttag
|
||||||
# - nakedret
|
# - nakedret
|
||||||
# - nestif
|
# - nestif
|
||||||
|
# - nilerr
|
||||||
|
# - nilnil
|
||||||
# - nlreturn
|
# - nlreturn
|
||||||
# - noctx
|
# - noctx
|
||||||
# - nolintlint
|
# - nolintlint
|
||||||
|
# - nonamedreturns
|
||||||
|
# - nosprintfhostport
|
||||||
|
# - paralleltest
|
||||||
|
# - perfsprint
|
||||||
|
# - predeclared
|
||||||
|
# - protogetter
|
||||||
|
# - reassign
|
||||||
|
# - revive
|
||||||
# - rowserrcheck
|
# - rowserrcheck
|
||||||
# - scopelint
|
|
||||||
# - sqlclosecheck
|
|
||||||
# - stylecheck
|
# - stylecheck
|
||||||
|
# - tagalign
|
||||||
|
# - tagliatelle
|
||||||
# - testpackage
|
# - testpackage
|
||||||
|
# - thelper
|
||||||
# - unparam
|
# - unparam
|
||||||
# - whitespace
|
# - usestdlibvars
|
||||||
|
# - varnamelen
|
||||||
|
# - wrapcheck
|
||||||
# - wsl
|
# - wsl
|
||||||
|
|
||||||
run:
|
run:
|
||||||
# default concurrency is a available CPU number.
|
# default concurrency is a available CPU number.
|
||||||
# concurrency: 4 # explicitly omit this value to fully utilize available resources.
|
# concurrency: 4 # explicitly omit this value to fully utilize available resources.
|
||||||
deadline: 5m
|
timeout: 5m
|
||||||
issues-exit-code: 1
|
issues-exit-code: 1
|
||||||
tests: false
|
tests: false
|
||||||
|
|
||||||
# output configuration options
|
# output configuration options
|
||||||
output:
|
output:
|
||||||
format: 'colored-line-number'
|
formats:
|
||||||
|
- format: 'colored-line-number'
|
||||||
print-issued-lines: true
|
print-issued-lines: true
|
||||||
print-linter-name: true
|
print-linter-name: true
|
||||||
|
|
||||||
issues:
|
issues:
|
||||||
exclude-rules:
|
exclude-rules:
|
||||||
|
- text: 'G115' # TODO: Either we should fix the issues or nuke the linter if it's bad
|
||||||
|
linters:
|
||||||
|
- gosec
|
||||||
# we aren't calling unknown URL
|
# we aren't calling unknown URL
|
||||||
- text: "G107" # G107: Url provided to HTTP request as taint input
|
- text: 'G107' # G107: Url provided to HTTP request as taint input
|
||||||
linters:
|
linters:
|
||||||
- gosec
|
- gosec
|
||||||
# as a web server that's expected to handle any template, this is totally in the hands of the user.
|
# as a web server that's expected to handle any template, this is totally in the hands of the user.
|
||||||
- text: "G203" # G203: Use of unescaped data in HTML templates
|
- text: 'G203' # G203: Use of unescaped data in HTML templates
|
||||||
linters:
|
linters:
|
||||||
- gosec
|
- gosec
|
||||||
# we're shelling out to known commands, not relying on user-defined input.
|
# we're shelling out to known commands, not relying on user-defined input.
|
||||||
- text: "G204" # G204: Audit use of command execution
|
- text: 'G204' # G204: Audit use of command execution
|
||||||
linters:
|
linters:
|
||||||
- gosec
|
- gosec
|
||||||
# the choice of weakrand is deliberate, hence the named import "weakrand"
|
# the choice of weakrand is deliberate, hence the named import "weakrand"
|
||||||
- path: modules/caddyhttp/reverseproxy/selectionpolicies.go
|
- path: modules/caddyhttp/reverseproxy/selectionpolicies.go
|
||||||
text: "G404" # G404: Insecure random number source (rand)
|
text: 'G404' # G404: Insecure random number source (rand)
|
||||||
linters:
|
linters:
|
||||||
- gosec
|
- gosec
|
||||||
- path: modules/caddyhttp/reverseproxy/streaming.go
|
- path: modules/caddyhttp/reverseproxy/streaming.go
|
||||||
text: "G404" # G404: Insecure random number source (rand)
|
text: 'G404' # G404: Insecure random number source (rand)
|
||||||
linters:
|
linters:
|
||||||
- gosec
|
- gosec
|
||||||
|
- path: modules/logging/filters.go
|
||||||
|
linters:
|
||||||
|
- dupl
|
||||||
|
- path: modules/caddyhttp/matchers.go
|
||||||
|
linters:
|
||||||
|
- dupl
|
||||||
|
- path: modules/caddyhttp/vars.go
|
||||||
|
linters:
|
||||||
|
- dupl
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- errcheck
|
||||||
|
|||||||
+15
-2
@@ -1,3 +1,5 @@
|
|||||||
|
version: 2
|
||||||
|
|
||||||
before:
|
before:
|
||||||
hooks:
|
hooks:
|
||||||
# The build is done in this particular way to build Caddy in a designated directory named in .gitignore.
|
# The build is done in this particular way to build Caddy in a designated directory named in .gitignore.
|
||||||
@@ -10,6 +12,9 @@ before:
|
|||||||
- mkdir -p caddy-build
|
- mkdir -p caddy-build
|
||||||
- cp cmd/caddy/main.go caddy-build/main.go
|
- cp cmd/caddy/main.go caddy-build/main.go
|
||||||
- /bin/sh -c 'cd ./caddy-build && go mod init caddy'
|
- /bin/sh -c 'cd ./caddy-build && go mod init caddy'
|
||||||
|
# prepare syso files for windows embedding
|
||||||
|
- /bin/sh -c 'for a in amd64 arm arm64; do XCADDY_SKIP_BUILD=1 GOOS=windows GOARCH=$a xcaddy build {{.Env.TAG}}; done'
|
||||||
|
- /bin/sh -c 'mv /tmp/buildenv_*/*.syso caddy-build'
|
||||||
# GoReleaser doesn't seem to offer {{.Tag}} at this stage, so we have to embed it into the env
|
# GoReleaser doesn't seem to offer {{.Tag}} at this stage, so we have to embed it into the env
|
||||||
# so we run: TAG=$(git describe --abbrev=0) goreleaser release --rm-dist --skip-publish --skip-validate
|
# so we run: TAG=$(git describe --abbrev=0) goreleaser release --rm-dist --skip-publish --skip-validate
|
||||||
- go mod edit -require=github.com/caddyserver/caddy/v2@{{.Env.TAG}} ./caddy-build/go.mod
|
- go mod edit -require=github.com/caddyserver/caddy/v2@{{.Env.TAG}} ./caddy-build/go.mod
|
||||||
@@ -29,7 +34,6 @@ builds:
|
|||||||
- env:
|
- env:
|
||||||
- CGO_ENABLED=0
|
- CGO_ENABLED=0
|
||||||
- GO111MODULE=on
|
- GO111MODULE=on
|
||||||
main: main.go
|
|
||||||
dir: ./caddy-build
|
dir: ./caddy-build
|
||||||
binary: caddy
|
binary: caddy
|
||||||
goos:
|
goos:
|
||||||
@@ -43,6 +47,7 @@ builds:
|
|||||||
- arm64
|
- arm64
|
||||||
- s390x
|
- s390x
|
||||||
- ppc64le
|
- ppc64le
|
||||||
|
- riscv64
|
||||||
goarm:
|
goarm:
|
||||||
- "5"
|
- "5"
|
||||||
- "6"
|
- "6"
|
||||||
@@ -54,14 +59,20 @@ builds:
|
|||||||
goarch: ppc64le
|
goarch: ppc64le
|
||||||
- goos: darwin
|
- goos: darwin
|
||||||
goarch: s390x
|
goarch: s390x
|
||||||
|
- goos: darwin
|
||||||
|
goarch: riscv64
|
||||||
- goos: windows
|
- goos: windows
|
||||||
goarch: ppc64le
|
goarch: ppc64le
|
||||||
- goos: windows
|
- goos: windows
|
||||||
goarch: s390x
|
goarch: s390x
|
||||||
|
- goos: windows
|
||||||
|
goarch: riscv64
|
||||||
- goos: freebsd
|
- goos: freebsd
|
||||||
goarch: ppc64le
|
goarch: ppc64le
|
||||||
- goos: freebsd
|
- goos: freebsd
|
||||||
goarch: s390x
|
goarch: s390x
|
||||||
|
- goos: freebsd
|
||||||
|
goarch: riscv64
|
||||||
- goos: freebsd
|
- goos: freebsd
|
||||||
goarch: arm
|
goarch: arm
|
||||||
goarm: "5"
|
goarm: "5"
|
||||||
@@ -70,6 +81,8 @@ builds:
|
|||||||
- -mod=readonly
|
- -mod=readonly
|
||||||
ldflags:
|
ldflags:
|
||||||
- -s -w
|
- -s -w
|
||||||
|
tags:
|
||||||
|
- nobadger
|
||||||
|
|
||||||
signs:
|
signs:
|
||||||
- cmd: cosign
|
- cmd: cosign
|
||||||
@@ -106,7 +119,7 @@ archives:
|
|||||||
{{- with .Mips }}_{{ . }}{{ end }}
|
{{- with .Mips }}_{{ . }}{{ end }}
|
||||||
{{- if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}
|
{{- if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}
|
||||||
|
|
||||||
# packge the 'caddy-build' directory into a tarball,
|
# package the 'caddy-build' directory into a tarball,
|
||||||
# allowing users to build the exact same set of files as ours.
|
# allowing users to build the exact same set of files as ours.
|
||||||
- id: source
|
- id: source
|
||||||
meta: true
|
meta: true
|
||||||
|
|||||||
@@ -56,7 +56,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
||||||
## [Features](https://caddyserver.com/v2)
|
## [Features](https://caddyserver.com/features)
|
||||||
|
|
||||||
- **Easy configuration** with the [Caddyfile](https://caddyserver.com/docs/caddyfile)
|
- **Easy configuration** with the [Caddyfile](https://caddyserver.com/docs/caddyfile)
|
||||||
- **Powerful configuration** with its [native JSON config](https://caddyserver.com/docs/json/)
|
- **Powerful configuration** with its [native JSON config](https://caddyserver.com/docs/json/)
|
||||||
@@ -75,7 +75,7 @@
|
|||||||
- **Runs anywhere** with **no external dependencies** (not even libc)
|
- **Runs anywhere** with **no external dependencies** (not even libc)
|
||||||
- Written in Go, a language with higher **memory safety guarantees** than other servers
|
- Written in Go, a language with higher **memory safety guarantees** than other servers
|
||||||
- Actually **fun to use**
|
- Actually **fun to use**
|
||||||
- So much more to [discover](https://caddyserver.com/v2)
|
- So much more to [discover](https://caddyserver.com/features)
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -87,7 +87,7 @@ See [our online documentation](https://caddyserver.com/docs/install) for other i
|
|||||||
|
|
||||||
Requirements:
|
Requirements:
|
||||||
|
|
||||||
- [Go 1.20 or newer](https://golang.org/dl/)
|
- [Go 1.22.3 or newer](https://golang.org/dl/)
|
||||||
|
|
||||||
### For development
|
### For development
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ import (
|
|||||||
"expvar"
|
"expvar"
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash"
|
"hash"
|
||||||
"hash/fnv"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -35,19 +34,21 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/caddyserver/certmagic"
|
"github.com/caddyserver/certmagic"
|
||||||
|
"github.com/cespare/xxhash/v2"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"go.uber.org/zap/zapcore"
|
"go.uber.org/zap/zapcore"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
// The hard-coded default `DefaultAdminListen` can be overidden
|
// The hard-coded default `DefaultAdminListen` can be overridden
|
||||||
// by setting the `CADDY_ADMIN` environment variable.
|
// by setting the `CADDY_ADMIN` environment variable.
|
||||||
// The environment variable may be used by packagers to change
|
// The environment variable may be used by packagers to change
|
||||||
// the default admin address to something more appropriate for
|
// the default admin address to something more appropriate for
|
||||||
@@ -213,7 +214,7 @@ type AdminPermissions struct {
|
|||||||
|
|
||||||
// newAdminHandler reads admin's config and returns an http.Handler suitable
|
// newAdminHandler reads admin's config and returns an http.Handler suitable
|
||||||
// for use in an admin endpoint server, which will be listening on listenAddr.
|
// for use in an admin endpoint server, which will be listening on listenAddr.
|
||||||
func (admin *AdminConfig) newAdminHandler(addr NetworkAddress, remote bool) adminHandler {
|
func (admin *AdminConfig) newAdminHandler(addr NetworkAddress, remote bool, ctx Context) adminHandler {
|
||||||
muxWrap := adminHandler{mux: http.NewServeMux()}
|
muxWrap := adminHandler{mux: http.NewServeMux()}
|
||||||
|
|
||||||
// secure the local or remote endpoint respectively
|
// secure the local or remote endpoint respectively
|
||||||
@@ -269,7 +270,6 @@ func (admin *AdminConfig) newAdminHandler(addr NetworkAddress, remote bool) admi
|
|||||||
// register third-party module endpoints
|
// register third-party module endpoints
|
||||||
for _, m := range GetModules("admin.api") {
|
for _, m := range GetModules("admin.api") {
|
||||||
router := m.New().(AdminRouter)
|
router := m.New().(AdminRouter)
|
||||||
handlerLabel := m.ID.Name()
|
|
||||||
for _, route := range router.Routes() {
|
for _, route := range router.Routes() {
|
||||||
addRoute(route.Pattern, handlerLabel, route.Handler)
|
addRoute(route.Pattern, handlerLabel, route.Handler)
|
||||||
}
|
}
|
||||||
@@ -312,7 +312,7 @@ func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
|
|||||||
}
|
}
|
||||||
if admin.Origins == nil {
|
if admin.Origins == nil {
|
||||||
if addr.isLoopback() {
|
if addr.isLoopback() {
|
||||||
if addr.IsUnixNetwork() {
|
if addr.IsUnixNetwork() || addr.IsFdNetwork() {
|
||||||
// RFC 2616, Section 14.26:
|
// RFC 2616, Section 14.26:
|
||||||
// "A client MUST include a Host header field in all HTTP/1.1 request
|
// "A client MUST include a Host header field in all HTTP/1.1 request
|
||||||
// messages. If the requested URI does not include an Internet host
|
// messages. If the requested URI does not include an Internet host
|
||||||
@@ -350,7 +350,7 @@ func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
|
|||||||
uniqueOrigins[net.JoinHostPort("127.0.0.1", addr.port())] = struct{}{}
|
uniqueOrigins[net.JoinHostPort("127.0.0.1", addr.port())] = struct{}{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !addr.IsUnixNetwork() {
|
if !addr.IsUnixNetwork() && !addr.IsFdNetwork() {
|
||||||
uniqueOrigins[addr.JoinHostPort(0)] = struct{}{}
|
uniqueOrigins[addr.JoinHostPort(0)] = struct{}{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -381,7 +381,9 @@ func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
|
|||||||
// for the admin endpoint exists in cfg, a default one is used, so
|
// for the admin endpoint exists in cfg, a default one is used, so
|
||||||
// that there is always an admin server (unless it is explicitly
|
// that there is always an admin server (unless it is explicitly
|
||||||
// configured to be disabled).
|
// configured to be disabled).
|
||||||
func replaceLocalAdminServer(cfg *Config) error {
|
// Critically note that some elements and functionality of the context
|
||||||
|
// may not be ready, e.g. storage. Tread carefully.
|
||||||
|
func replaceLocalAdminServer(cfg *Config, ctx Context) error {
|
||||||
// always* be sure to close down the old admin endpoint
|
// always* be sure to close down the old admin endpoint
|
||||||
// as gracefully as possible, even if the new one is
|
// as gracefully as possible, even if the new one is
|
||||||
// disabled -- careful to use reference to the current
|
// disabled -- careful to use reference to the current
|
||||||
@@ -423,7 +425,7 @@ func replaceLocalAdminServer(cfg *Config) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
handler := cfg.Admin.newAdminHandler(addr, false)
|
handler := cfg.Admin.newAdminHandler(addr, false, ctx)
|
||||||
|
|
||||||
ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{})
|
ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -474,7 +476,6 @@ func manageIdentity(ctx Context, cfg *Config) error {
|
|||||||
// import the caddytls package -- but it works
|
// import the caddytls package -- but it works
|
||||||
if cfg.Admin.Identity.IssuersRaw == nil {
|
if cfg.Admin.Identity.IssuersRaw == nil {
|
||||||
cfg.Admin.Identity.IssuersRaw = []json.RawMessage{
|
cfg.Admin.Identity.IssuersRaw = []json.RawMessage{
|
||||||
json.RawMessage(`{"module": "zerossl"}`),
|
|
||||||
json.RawMessage(`{"module": "acme"}`),
|
json.RawMessage(`{"module": "acme"}`),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -545,7 +546,7 @@ func replaceRemoteAdminServer(ctx Context, cfg *Config) error {
|
|||||||
|
|
||||||
// make the HTTP handler but disable Host/Origin enforcement
|
// make the HTTP handler but disable Host/Origin enforcement
|
||||||
// because we are using TLS authentication instead
|
// because we are using TLS authentication instead
|
||||||
handler := cfg.Admin.newAdminHandler(addr, true)
|
handler := cfg.Admin.newAdminHandler(addr, true, ctx)
|
||||||
|
|
||||||
// create client certificate pool for TLS mutual auth, and extract public keys
|
// create client certificate pool for TLS mutual auth, and extract public keys
|
||||||
// so that we can enforce access controls at the application layer
|
// so that we can enforce access controls at the application layer
|
||||||
@@ -676,13 +677,7 @@ func (remote RemoteAdmin) enforceAccessControls(r *http.Request) error {
|
|||||||
// key recognized; make sure its HTTP request is permitted
|
// key recognized; make sure its HTTP request is permitted
|
||||||
for _, accessPerm := range adminAccess.Permissions {
|
for _, accessPerm := range adminAccess.Permissions {
|
||||||
// verify method
|
// verify method
|
||||||
methodFound := accessPerm.Methods == nil
|
methodFound := accessPerm.Methods == nil || slices.Contains(accessPerm.Methods, r.Method)
|
||||||
for _, method := range accessPerm.Methods {
|
|
||||||
if method == r.Method {
|
|
||||||
methodFound = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !methodFound {
|
if !methodFound {
|
||||||
return APIError{
|
return APIError{
|
||||||
HTTPStatus: http.StatusForbidden,
|
HTTPStatus: http.StatusForbidden,
|
||||||
@@ -878,13 +873,9 @@ func (h adminHandler) handleError(w http.ResponseWriter, r *http.Request, err er
|
|||||||
// a trustworthy/expected value. This helps to mitigate DNS
|
// a trustworthy/expected value. This helps to mitigate DNS
|
||||||
// rebinding attacks.
|
// rebinding attacks.
|
||||||
func (h adminHandler) checkHost(r *http.Request) error {
|
func (h adminHandler) checkHost(r *http.Request) error {
|
||||||
var allowed bool
|
allowed := slices.ContainsFunc(h.allowedOrigins, func(u *url.URL) bool {
|
||||||
for _, allowedOrigin := range h.allowedOrigins {
|
return r.Host == u.Host
|
||||||
if r.Host == allowedOrigin.Host {
|
})
|
||||||
allowed = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !allowed {
|
if !allowed {
|
||||||
return APIError{
|
return APIError{
|
||||||
HTTPStatus: http.StatusForbidden,
|
HTTPStatus: http.StatusForbidden,
|
||||||
@@ -946,7 +937,7 @@ func (h adminHandler) originAllowed(origin *url.URL) bool {
|
|||||||
|
|
||||||
// etagHasher returns a the hasher we used on the config to both
|
// etagHasher returns a the hasher we used on the config to both
|
||||||
// produce and verify ETags.
|
// produce and verify ETags.
|
||||||
func etagHasher() hash.Hash32 { return fnv.New32a() }
|
func etagHasher() hash.Hash { return xxhash.New() }
|
||||||
|
|
||||||
// makeEtag returns an Etag header value (including quotes) for
|
// makeEtag returns an Etag header value (including quotes) for
|
||||||
// the given config path and hash of contents at that path.
|
// the given config path and hash of contents at that path.
|
||||||
@@ -954,17 +945,28 @@ func makeEtag(path string, hash hash.Hash) string {
|
|||||||
return fmt.Sprintf(`"%s %x"`, path, hash.Sum(nil))
|
return fmt.Sprintf(`"%s %x"`, path, hash.Sum(nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// This buffer pool is used to keep buffers for
|
||||||
|
// reading the config file during eTag header generation
|
||||||
|
var bufferPool = sync.Pool{
|
||||||
|
New: func() any {
|
||||||
|
return new(bytes.Buffer)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
func handleConfig(w http.ResponseWriter, r *http.Request) error {
|
func handleConfig(w http.ResponseWriter, r *http.Request) error {
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
// Set the ETag as a trailer header.
|
|
||||||
// The alternative is to write the config to a buffer, and
|
|
||||||
// then hash that.
|
|
||||||
w.Header().Set("Trailer", "ETag")
|
|
||||||
|
|
||||||
hash := etagHasher()
|
hash := etagHasher()
|
||||||
configWriter := io.MultiWriter(w, hash)
|
|
||||||
|
// Read the config into a buffer instead of writing directly to
|
||||||
|
// the response writer, as we want to set the ETag as the header,
|
||||||
|
// not the trailer.
|
||||||
|
buf := bufferPool.Get().(*bytes.Buffer)
|
||||||
|
buf.Reset()
|
||||||
|
defer bufferPool.Put(buf)
|
||||||
|
|
||||||
|
configWriter := io.MultiWriter(buf, hash)
|
||||||
err := readConfig(r.URL.Path, configWriter)
|
err := readConfig(r.URL.Path, configWriter)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return APIError{HTTPStatus: http.StatusBadRequest, Err: err}
|
return APIError{HTTPStatus: http.StatusBadRequest, Err: err}
|
||||||
@@ -973,6 +975,10 @@ func handleConfig(w http.ResponseWriter, r *http.Request) error {
|
|||||||
// we could consider setting up a sync.Pool for the summed
|
// we could consider setting up a sync.Pool for the summed
|
||||||
// hashes to reduce GC pressure.
|
// hashes to reduce GC pressure.
|
||||||
w.Header().Set("Etag", makeEtag(r.URL.Path, hash))
|
w.Header().Set("Etag", makeEtag(r.URL.Path, hash))
|
||||||
|
_, err = w.Write(buf.Bytes())
|
||||||
|
if err != nil {
|
||||||
|
return APIError{HTTPStatus: http.StatusInternalServerError, Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
@@ -1196,15 +1202,27 @@ traverseLoop:
|
|||||||
}
|
}
|
||||||
case http.MethodPut:
|
case http.MethodPut:
|
||||||
if _, ok := v[part]; ok {
|
if _, ok := v[part]; ok {
|
||||||
return fmt.Errorf("[%s] key already exists: %s", path, part)
|
return APIError{
|
||||||
|
HTTPStatus: http.StatusConflict,
|
||||||
|
Err: fmt.Errorf("[%s] key already exists: %s", path, part),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
v[part] = val
|
v[part] = val
|
||||||
case http.MethodPatch:
|
case http.MethodPatch:
|
||||||
if _, ok := v[part]; !ok {
|
if _, ok := v[part]; !ok {
|
||||||
return fmt.Errorf("[%s] key does not exist: %s", path, part)
|
return APIError{
|
||||||
|
HTTPStatus: http.StatusNotFound,
|
||||||
|
Err: fmt.Errorf("[%s] key does not exist: %s", path, part),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
v[part] = val
|
v[part] = val
|
||||||
case http.MethodDelete:
|
case http.MethodDelete:
|
||||||
|
if _, ok := v[part]; !ok {
|
||||||
|
return APIError{
|
||||||
|
HTTPStatus: http.StatusNotFound,
|
||||||
|
Err: fmt.Errorf("[%s] key does not exist: %s", path, part),
|
||||||
|
}
|
||||||
|
}
|
||||||
delete(v, part)
|
delete(v, part)
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("unrecognized method %s", method)
|
return fmt.Errorf("unrecognized method %s", method)
|
||||||
@@ -1346,7 +1364,7 @@ var (
|
|||||||
// will get deleted before the process gracefully exits.
|
// will get deleted before the process gracefully exits.
|
||||||
func PIDFile(filename string) error {
|
func PIDFile(filename string) error {
|
||||||
pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
|
pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
|
||||||
err := os.WriteFile(filename, pid, 0600)
|
err := os.WriteFile(filename, pid, 0o600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,6 +75,12 @@ func TestUnsyncedConfigAccess(t *testing.T) {
|
|||||||
path: "/bar/qq",
|
path: "/bar/qq",
|
||||||
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c"]}`,
|
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c"]}`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
path: "/bar/qq",
|
||||||
|
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c"]}`,
|
||||||
|
shouldErr: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
path: "/list",
|
path: "/list",
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -34,10 +35,12 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2/notify"
|
|
||||||
"github.com/caddyserver/certmagic"
|
"github.com/caddyserver/certmagic"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2/internal/filesystems"
|
||||||
|
"github.com/caddyserver/caddy/v2/notify"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config is the top (or beginning) of the Caddy configuration structure.
|
// Config is the top (or beginning) of the Caddy configuration structure.
|
||||||
@@ -82,6 +85,9 @@ type Config struct {
|
|||||||
storage certmagic.Storage
|
storage certmagic.Storage
|
||||||
|
|
||||||
cancelFunc context.CancelFunc
|
cancelFunc context.CancelFunc
|
||||||
|
|
||||||
|
// filesystems is a dict of filesystems that will later be loaded from and added to.
|
||||||
|
filesystems FileSystems
|
||||||
}
|
}
|
||||||
|
|
||||||
// App is a thing that Caddy runs.
|
// App is a thing that Caddy runs.
|
||||||
@@ -356,13 +362,13 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
|
|||||||
newCfg.Admin.Config.Persist == nil ||
|
newCfg.Admin.Config.Persist == nil ||
|
||||||
*newCfg.Admin.Config.Persist) {
|
*newCfg.Admin.Config.Persist) {
|
||||||
dir := filepath.Dir(ConfigAutosavePath)
|
dir := filepath.Dir(ConfigAutosavePath)
|
||||||
err := os.MkdirAll(dir, 0700)
|
err := os.MkdirAll(dir, 0o700)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Log().Error("unable to create folder for config autosave",
|
Log().Error("unable to create folder for config autosave",
|
||||||
zap.String("dir", dir),
|
zap.String("dir", dir),
|
||||||
zap.Error(err))
|
zap.Error(err))
|
||||||
} else {
|
} else {
|
||||||
err := os.WriteFile(ConfigAutosavePath, cfgJSON, 0600)
|
err := os.WriteFile(ConfigAutosavePath, cfgJSON, 0o600)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
Log().Info("autosaved config (load with --resume flag)", zap.String("file", ConfigAutosavePath))
|
Log().Info("autosaved config (load with --resume flag)", zap.String("file", ConfigAutosavePath))
|
||||||
} else {
|
} else {
|
||||||
@@ -391,6 +397,62 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
|
|||||||
// will want to use Run instead, which also
|
// will want to use Run instead, which also
|
||||||
// updates the config's raw state.
|
// updates the config's raw state.
|
||||||
func run(newCfg *Config, start bool) (Context, error) {
|
func run(newCfg *Config, start bool) (Context, error) {
|
||||||
|
ctx, err := provisionContext(newCfg, start)
|
||||||
|
if err != nil {
|
||||||
|
globalMetrics.configSuccess.Set(0)
|
||||||
|
return ctx, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !start {
|
||||||
|
return ctx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provision any admin routers which may need to access
|
||||||
|
// some of the other apps at runtime
|
||||||
|
err = ctx.cfg.Admin.provisionAdminRouters(ctx)
|
||||||
|
if err != nil {
|
||||||
|
globalMetrics.configSuccess.Set(0)
|
||||||
|
return ctx, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start
|
||||||
|
err = func() error {
|
||||||
|
started := make([]string, 0, len(ctx.cfg.apps))
|
||||||
|
for name, a := range ctx.cfg.apps {
|
||||||
|
err := a.Start()
|
||||||
|
if err != nil {
|
||||||
|
// an app failed to start, so we need to stop
|
||||||
|
// all other apps that were already started
|
||||||
|
for _, otherAppName := range started {
|
||||||
|
err2 := ctx.cfg.apps[otherAppName].Stop()
|
||||||
|
if err2 != nil {
|
||||||
|
err = fmt.Errorf("%v; additionally, aborting app %s: %v",
|
||||||
|
err, otherAppName, err2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s app module: start: %v", name, err)
|
||||||
|
}
|
||||||
|
started = append(started, name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}()
|
||||||
|
if err != nil {
|
||||||
|
globalMetrics.configSuccess.Set(0)
|
||||||
|
return ctx, err
|
||||||
|
}
|
||||||
|
globalMetrics.configSuccess.Set(1)
|
||||||
|
globalMetrics.configSuccessTime.SetToCurrentTime()
|
||||||
|
// now that the user's config is running, finish setting up anything else,
|
||||||
|
// such as remote admin endpoint, config loader, etc.
|
||||||
|
return ctx, finishSettingUp(ctx, ctx.cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// provisionContext creates a new context from the given configuration and provisions
|
||||||
|
// storage and apps.
|
||||||
|
// If `newCfg` is nil a new empty configuration will be created.
|
||||||
|
// If `replaceAdminServer` is true any currently active admin server will be replaced
|
||||||
|
// with a new admin server based on the provided configuration.
|
||||||
|
func provisionContext(newCfg *Config, replaceAdminServer bool) (Context, error) {
|
||||||
// because we will need to roll back any state
|
// because we will need to roll back any state
|
||||||
// modifications if this function errors, we
|
// modifications if this function errors, we
|
||||||
// keep a single error value and scope all
|
// keep a single error value and scope all
|
||||||
@@ -413,6 +475,7 @@ func run(newCfg *Config, start bool) (Context, error) {
|
|||||||
ctx, cancel := NewContext(Context{Context: context.Background(), cfg: newCfg})
|
ctx, cancel := NewContext(Context{Context: context.Background(), cfg: newCfg})
|
||||||
defer func() {
|
defer func() {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
globalMetrics.configSuccess.Set(0)
|
||||||
// if there were any errors during startup,
|
// if there were any errors during startup,
|
||||||
// we should cancel the new context we created
|
// we should cancel the new context we created
|
||||||
// since the associated config won't be used;
|
// since the associated config won't be used;
|
||||||
@@ -438,13 +501,16 @@ func run(newCfg *Config, start bool) (Context, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// start the admin endpoint (and stop any prior one)
|
// start the admin endpoint (and stop any prior one)
|
||||||
if start {
|
if replaceAdminServer {
|
||||||
err = replaceLocalAdminServer(newCfg)
|
err = replaceLocalAdminServer(newCfg, ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ctx, fmt.Errorf("starting caddy administration endpoint: %v", err)
|
return ctx, fmt.Errorf("starting caddy administration endpoint: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// create the new filesystem map
|
||||||
|
newCfg.filesystems = &filesystems.FilesystemMap{}
|
||||||
|
|
||||||
// prepare the new config for use
|
// prepare the new config for use
|
||||||
newCfg.apps = make(map[string]App)
|
newCfg.apps = make(map[string]App)
|
||||||
|
|
||||||
@@ -482,49 +548,16 @@ func run(newCfg *Config, start bool) (Context, error) {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}()
|
}()
|
||||||
if err != nil {
|
|
||||||
return ctx, err
|
return ctx, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !start {
|
// ProvisionContext creates a new context from the configuration and provisions storage
|
||||||
return ctx, nil
|
// and app modules.
|
||||||
}
|
// The function is intended for testing and advanced use cases only, typically `Run` should be
|
||||||
|
// use to ensure a fully functional caddy instance.
|
||||||
// Provision any admin routers which may need to access
|
// EXPERIMENTAL: While this is public the interface and implementation details of this function may change.
|
||||||
// some of the other apps at runtime
|
func ProvisionContext(newCfg *Config) (Context, error) {
|
||||||
err = newCfg.Admin.provisionAdminRouters(ctx)
|
return provisionContext(newCfg, false)
|
||||||
if err != nil {
|
|
||||||
return ctx, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start
|
|
||||||
err = func() error {
|
|
||||||
started := make([]string, 0, len(newCfg.apps))
|
|
||||||
for name, a := range newCfg.apps {
|
|
||||||
err := a.Start()
|
|
||||||
if err != nil {
|
|
||||||
// an app failed to start, so we need to stop
|
|
||||||
// all other apps that were already started
|
|
||||||
for _, otherAppName := range started {
|
|
||||||
err2 := newCfg.apps[otherAppName].Stop()
|
|
||||||
if err2 != nil {
|
|
||||||
err = fmt.Errorf("%v; additionally, aborting app %s: %v",
|
|
||||||
err, otherAppName, err2)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf("%s app module: start: %v", name, err)
|
|
||||||
}
|
|
||||||
started = append(started, name)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}()
|
|
||||||
if err != nil {
|
|
||||||
return ctx, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// now that the user's config is running, finish setting up anything else,
|
|
||||||
// such as remote admin endpoint, config loader, etc.
|
|
||||||
return ctx, finishSettingUp(ctx, newCfg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// finishSettingUp should be run after all apps have successfully started.
|
// finishSettingUp should be run after all apps have successfully started.
|
||||||
@@ -706,6 +739,7 @@ func exitProcess(ctx context.Context, logger *zap.Logger) {
|
|||||||
logger.Warn("exiting; byeee!! 👋")
|
logger.Warn("exiting; byeee!! 👋")
|
||||||
|
|
||||||
exitCode := ExitCodeSuccess
|
exitCode := ExitCodeSuccess
|
||||||
|
lastContext := ActiveContext()
|
||||||
|
|
||||||
// stop all apps
|
// stop all apps
|
||||||
if err := Stop(); err != nil {
|
if err := Stop(); err != nil {
|
||||||
@@ -727,6 +761,16 @@ func exitProcess(ctx context.Context, logger *zap.Logger) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// execute any process-exit callbacks
|
||||||
|
for _, exitFunc := range lastContext.exitFuncs {
|
||||||
|
exitFunc(ctx)
|
||||||
|
}
|
||||||
|
exitFuncsMu.Lock()
|
||||||
|
for _, exitFunc := range exitFuncs {
|
||||||
|
exitFunc(ctx)
|
||||||
|
}
|
||||||
|
exitFuncsMu.Unlock()
|
||||||
|
|
||||||
// shut down admin endpoint(s) in goroutines so that
|
// shut down admin endpoint(s) in goroutines so that
|
||||||
// if this function was called from an admin handler,
|
// if this function was called from an admin handler,
|
||||||
// it has a chance to return gracefully
|
// it has a chance to return gracefully
|
||||||
@@ -765,6 +809,23 @@ var exiting = new(int32) // accessed atomically
|
|||||||
// EXPERIMENTAL API: subject to change or removal.
|
// EXPERIMENTAL API: subject to change or removal.
|
||||||
func Exiting() bool { return atomic.LoadInt32(exiting) == 1 }
|
func Exiting() bool { return atomic.LoadInt32(exiting) == 1 }
|
||||||
|
|
||||||
|
// OnExit registers a callback to invoke during process exit.
|
||||||
|
// This registration is PROCESS-GLOBAL, meaning that each
|
||||||
|
// function should only be registered once forever, NOT once
|
||||||
|
// per config load (etc).
|
||||||
|
//
|
||||||
|
// EXPERIMENTAL API: subject to change or removal.
|
||||||
|
func OnExit(f func(context.Context)) {
|
||||||
|
exitFuncsMu.Lock()
|
||||||
|
exitFuncs = append(exitFuncs, f)
|
||||||
|
exitFuncsMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
exitFuncs []func(context.Context)
|
||||||
|
exitFuncsMu sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
// Duration can be an integer or a string. An integer is
|
// Duration can be an integer or a string. An integer is
|
||||||
// interpreted as nanoseconds. If a string, it is a Go
|
// interpreted as nanoseconds. If a string, it is a Go
|
||||||
// time.Duration value such as `300ms`, `1.5h`, or `2h45m`;
|
// time.Duration value such as `300ms`, `1.5h`, or `2h45m`;
|
||||||
@@ -824,14 +885,19 @@ func ParseDuration(s string) (time.Duration, error) {
|
|||||||
// regardless of storage configuration, since each instance is intended to
|
// regardless of storage configuration, since each instance is intended to
|
||||||
// have its own unique ID.
|
// have its own unique ID.
|
||||||
func InstanceID() (uuid.UUID, error) {
|
func InstanceID() (uuid.UUID, error) {
|
||||||
uuidFilePath := filepath.Join(AppDataDir(), "instance.uuid")
|
appDataDir := AppDataDir()
|
||||||
|
uuidFilePath := filepath.Join(appDataDir, "instance.uuid")
|
||||||
uuidFileBytes, err := os.ReadFile(uuidFilePath)
|
uuidFileBytes, err := os.ReadFile(uuidFilePath)
|
||||||
if os.IsNotExist(err) {
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
uuid, err := uuid.NewRandom()
|
uuid, err := uuid.NewRandom()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return uuid, err
|
return uuid, err
|
||||||
}
|
}
|
||||||
err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0600)
|
err = os.MkdirAll(appDataDir, 0o700)
|
||||||
|
if err != nil {
|
||||||
|
return uuid, err
|
||||||
|
}
|
||||||
|
err = os.WriteFile(uuidFilePath, []byte(uuid.String()), 0o600)
|
||||||
return uuid, err
|
return uuid, err
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return [16]byte{}, err
|
return [16]byte{}, err
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
|
|||||||
return nil, warnings, err
|
return nil, warnings, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// lint check: see if input was properly formatted; sometimes messy files files parse
|
// lint check: see if input was properly formatted; sometimes messy files parse
|
||||||
// successfully but result in logical errors (the Caddyfile is a bad format, I'm sorry)
|
// successfully but result in logical errors (the Caddyfile is a bad format, I'm sorry)
|
||||||
if warning, different := FormattingDifference(filename, body); different {
|
if warning, different := FormattingDifference(filename, body); different {
|
||||||
warnings = append(warnings, warning)
|
warnings = append(warnings, warning)
|
||||||
@@ -92,30 +92,26 @@ func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bo
|
|||||||
}, true
|
}, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unmarshaler is a type that can unmarshal
|
// Unmarshaler is a type that can unmarshal Caddyfile tokens to
|
||||||
// Caddyfile tokens to set itself up for a
|
// set itself up for a JSON encoding. The goal of an unmarshaler
|
||||||
// JSON encoding. The goal of an unmarshaler
|
// is not to set itself up for actual use, but to set itself up for
|
||||||
// is not to set itself up for actual use,
|
// being marshaled into JSON. Caddyfile-unmarshaled values will not
|
||||||
// but to set itself up for being marshaled
|
// be used directly; they will be encoded as JSON and then used from
|
||||||
// into JSON. Caddyfile-unmarshaled values
|
// that. Implementations _may_ be able to support multiple segments
|
||||||
// will not be used directly; they will be
|
// (instances of their directive or batch of tokens); typically this
|
||||||
// encoded as JSON and then used from that.
|
// means wrapping parsing logic in a loop: `for d.Next() { ... }`.
|
||||||
// Implementations must be able to support
|
// More commonly, only a single segment is supported, so a simple
|
||||||
// multiple segments (instances of their
|
// `d.Next()` at the start should be used to consume the module
|
||||||
// directive or batch of tokens); typically
|
// identifier token (directive name, etc).
|
||||||
// this means wrapping all token logic in
|
|
||||||
// a loop: `for d.Next() { ... }`.
|
|
||||||
type Unmarshaler interface {
|
type Unmarshaler interface {
|
||||||
UnmarshalCaddyfile(d *Dispenser) error
|
UnmarshalCaddyfile(d *Dispenser) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServerType is a type that can evaluate a Caddyfile and set up a caddy config.
|
// ServerType is a type that can evaluate a Caddyfile and set up a caddy config.
|
||||||
type ServerType interface {
|
type ServerType interface {
|
||||||
// Setup takes the server blocks which
|
// Setup takes the server blocks which contain tokens,
|
||||||
// contain tokens, as well as options
|
// as well as options (e.g. CLI flags) and creates a
|
||||||
// (e.g. CLI flags) and creates a Caddy
|
// Caddy config, along with any warnings or an error.
|
||||||
// config, along with any warnings or
|
|
||||||
// an error.
|
|
||||||
Setup([]ServerBlock, map[string]any) (*caddy.Config, []caddyconfig.Warning, error)
|
Setup([]ServerBlock, map[string]any) (*caddy.Config, []caddyconfig.Warning, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ type Dispenser struct {
|
|||||||
tokens []Token
|
tokens []Token
|
||||||
cursor int
|
cursor int
|
||||||
nesting int
|
nesting int
|
||||||
|
|
||||||
|
// A map of arbitrary context data that can be used
|
||||||
|
// to pass through some information to unmarshalers.
|
||||||
|
context map[string]any
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewDispenser returns a Dispenser filled with the given tokens.
|
// NewDispenser returns a Dispenser filled with the given tokens.
|
||||||
@@ -391,27 +395,27 @@ func (d *Dispenser) Reset() {
|
|||||||
// an argument.
|
// an argument.
|
||||||
func (d *Dispenser) ArgErr() error {
|
func (d *Dispenser) ArgErr() error {
|
||||||
if d.Val() == "{" {
|
if d.Val() == "{" {
|
||||||
return d.Err("Unexpected token '{', expecting argument")
|
return d.Err("unexpected token '{', expecting argument")
|
||||||
}
|
}
|
||||||
return d.Errf("Wrong argument count or unexpected line ending after '%s'", d.Val())
|
return d.Errf("wrong argument count or unexpected line ending after '%s'", d.Val())
|
||||||
}
|
}
|
||||||
|
|
||||||
// SyntaxErr creates a generic syntax error which explains what was
|
// SyntaxErr creates a generic syntax error which explains what was
|
||||||
// found and what was expected.
|
// found and what was expected.
|
||||||
func (d *Dispenser) SyntaxErr(expected string) error {
|
func (d *Dispenser) SyntaxErr(expected string) error {
|
||||||
msg := fmt.Sprintf("%s:%d - Syntax error: Unexpected token '%s', expecting '%s', import chain: ['%s']", d.File(), d.Line(), d.Val(), expected, strings.Join(d.Token().imports, "','"))
|
msg := fmt.Sprintf("syntax error: unexpected token '%s', expecting '%s', at %s:%d import chain: ['%s']", d.Val(), expected, d.File(), d.Line(), strings.Join(d.Token().imports, "','"))
|
||||||
return errors.New(msg)
|
return errors.New(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EOFErr returns an error indicating that the dispenser reached
|
// EOFErr returns an error indicating that the dispenser reached
|
||||||
// the end of the input when searching for the next token.
|
// the end of the input when searching for the next token.
|
||||||
func (d *Dispenser) EOFErr() error {
|
func (d *Dispenser) EOFErr() error {
|
||||||
return d.Errf("Unexpected EOF")
|
return d.Errf("unexpected EOF")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Err generates a custom parse-time error with a message of msg.
|
// Err generates a custom parse-time error with a message of msg.
|
||||||
func (d *Dispenser) Err(msg string) error {
|
func (d *Dispenser) Err(msg string) error {
|
||||||
return d.Errf(msg)
|
return d.WrapErr(errors.New(msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Errf is like Err, but for formatted error messages
|
// Errf is like Err, but for formatted error messages
|
||||||
@@ -421,7 +425,10 @@ func (d *Dispenser) Errf(format string, args ...any) error {
|
|||||||
|
|
||||||
// WrapErr takes an existing error and adds the Caddyfile file and line number.
|
// WrapErr takes an existing error and adds the Caddyfile file and line number.
|
||||||
func (d *Dispenser) WrapErr(err error) error {
|
func (d *Dispenser) WrapErr(err error) error {
|
||||||
return fmt.Errorf("%s:%d - Error during parsing: %w, import chain: ['%s']", d.File(), d.Line(), err, strings.Join(d.Token().imports, "','"))
|
if len(d.Token().imports) > 0 {
|
||||||
|
return fmt.Errorf("%w, at %s:%d import chain ['%s']", err, d.File(), d.Line(), strings.Join(d.Token().imports, "','"))
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%w, at %s:%d", err, d.File(), d.Line())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes the current token and returns the updated slice
|
// Delete deletes the current token and returns the updated slice
|
||||||
@@ -451,6 +458,34 @@ func (d *Dispenser) DeleteN(amount int) []Token {
|
|||||||
return d.tokens
|
return d.tokens
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetContext sets a key-value pair in the context map.
|
||||||
|
func (d *Dispenser) SetContext(key string, value any) {
|
||||||
|
if d.context == nil {
|
||||||
|
d.context = make(map[string]any)
|
||||||
|
}
|
||||||
|
d.context[key] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetContext gets the value of a key in the context map.
|
||||||
|
func (d *Dispenser) GetContext(key string) any {
|
||||||
|
if d.context == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return d.context[key]
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetContextString gets the value of a key in the context map
|
||||||
|
// as a string, or an empty string if the key does not exist.
|
||||||
|
func (d *Dispenser) GetContextString(key string) string {
|
||||||
|
if d.context == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if val, ok := d.context[key].(string); ok {
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
// isNewLine determines whether the current token is on a different
|
// isNewLine determines whether the current token is on a different
|
||||||
// line (higher line number) than the previous token. It handles imported
|
// line (higher line number) than the previous token. It handles imported
|
||||||
// tokens correctly. If there isn't a previous token, it returns true.
|
// tokens correctly. If there isn't a previous token, it returns true.
|
||||||
@@ -482,3 +517,5 @@ func (d *Dispenser) isNextOnNewLine() bool {
|
|||||||
next := d.tokens[d.cursor+1]
|
next := d.tokens[d.cursor+1]
|
||||||
return isNextOnNewLine(curr, next)
|
return isNextOnNewLine(curr, next)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MatcherNameCtxKey = "matcher_name"
|
||||||
|
|||||||
@@ -305,7 +305,7 @@ func TestDispenser_ArgErr_Err(t *testing.T) {
|
|||||||
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
|
t.Errorf("Expected error message with custom message in it ('foobar'); got '%v'", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var ErrBarIsFull = errors.New("bar is full")
|
ErrBarIsFull := errors.New("bar is full")
|
||||||
bookingError := d.Errf("unable to reserve: %w", ErrBarIsFull)
|
bookingError := d.Errf("unable to reserve: %w", ErrBarIsFull)
|
||||||
if !errors.Is(bookingError, ErrBarIsFull) {
|
if !errors.Is(bookingError, ErrBarIsFull) {
|
||||||
t.Errorf("Errf(): should be able to unwrap the error chain")
|
t.Errorf("Errf(): should be able to unwrap the error chain")
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ package caddyfile
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"io"
|
"io"
|
||||||
|
"slices"
|
||||||
"unicode"
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -31,6 +32,14 @@ func Format(input []byte) []byte {
|
|||||||
out := new(bytes.Buffer)
|
out := new(bytes.Buffer)
|
||||||
rdr := bytes.NewReader(input)
|
rdr := bytes.NewReader(input)
|
||||||
|
|
||||||
|
type heredocState int
|
||||||
|
|
||||||
|
const (
|
||||||
|
heredocClosed heredocState = 0
|
||||||
|
heredocOpening heredocState = 1
|
||||||
|
heredocOpened heredocState = 2
|
||||||
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
last rune // the last character that was written to the result
|
last rune // the last character that was written to the result
|
||||||
|
|
||||||
@@ -47,6 +56,11 @@ func Format(input []byte) []byte {
|
|||||||
quoted bool // whether we're in a quoted segment
|
quoted bool // whether we're in a quoted segment
|
||||||
escaped bool // whether current char is escaped
|
escaped bool // whether current char is escaped
|
||||||
|
|
||||||
|
heredoc heredocState // whether we're in a heredoc
|
||||||
|
heredocEscaped bool // whether heredoc is escaped
|
||||||
|
heredocMarker []rune
|
||||||
|
heredocClosingMarker []rune
|
||||||
|
|
||||||
nesting int // indentation level
|
nesting int // indentation level
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -75,6 +89,62 @@ func Format(input []byte) []byte {
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// detect whether we have the start of a heredoc
|
||||||
|
if !quoted && !(heredoc != heredocClosed || heredocEscaped) &&
|
||||||
|
space && last == '<' && ch == '<' {
|
||||||
|
write(ch)
|
||||||
|
heredoc = heredocOpening
|
||||||
|
space = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if heredoc == heredocOpening {
|
||||||
|
if ch == '\n' {
|
||||||
|
if len(heredocMarker) > 0 && heredocMarkerRegexp.MatchString(string(heredocMarker)) {
|
||||||
|
heredoc = heredocOpened
|
||||||
|
} else {
|
||||||
|
heredocMarker = nil
|
||||||
|
heredoc = heredocClosed
|
||||||
|
nextLine()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
write(ch)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if unicode.IsSpace(ch) {
|
||||||
|
// a space means it's just a regular token and not a heredoc
|
||||||
|
heredocMarker = nil
|
||||||
|
heredoc = heredocClosed
|
||||||
|
} else {
|
||||||
|
heredocMarker = append(heredocMarker, ch)
|
||||||
|
write(ch)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// if we're in a heredoc, all characters are read&write as-is
|
||||||
|
if heredoc == heredocOpened {
|
||||||
|
heredocClosingMarker = append(heredocClosingMarker, ch)
|
||||||
|
if len(heredocClosingMarker) > len(heredocMarker)+1 { // We assert that the heredocClosingMarker is followed by a unicode.Space
|
||||||
|
heredocClosingMarker = heredocClosingMarker[1:]
|
||||||
|
}
|
||||||
|
// check if we're done
|
||||||
|
if unicode.IsSpace(ch) && slices.Equal(heredocClosingMarker[:len(heredocClosingMarker)-1], heredocMarker) {
|
||||||
|
heredocMarker = nil
|
||||||
|
heredocClosingMarker = nil
|
||||||
|
heredoc = heredocClosed
|
||||||
|
} else {
|
||||||
|
write(ch)
|
||||||
|
if ch == '\n' {
|
||||||
|
heredocClosingMarker = heredocClosingMarker[:0]
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if last == '<' && space {
|
||||||
|
space = false
|
||||||
|
}
|
||||||
|
|
||||||
if comment {
|
if comment {
|
||||||
if ch == '\n' {
|
if ch == '\n' {
|
||||||
comment = false
|
comment = false
|
||||||
@@ -98,6 +168,9 @@ func Format(input []byte) []byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if escaped {
|
if escaped {
|
||||||
|
if ch == '<' {
|
||||||
|
heredocEscaped = true
|
||||||
|
}
|
||||||
write(ch)
|
write(ch)
|
||||||
escaped = false
|
escaped = false
|
||||||
continue
|
continue
|
||||||
@@ -117,6 +190,7 @@ func Format(input []byte) []byte {
|
|||||||
|
|
||||||
if unicode.IsSpace(ch) {
|
if unicode.IsSpace(ch) {
|
||||||
space = true
|
space = true
|
||||||
|
heredocEscaped = false
|
||||||
if ch == '\n' {
|
if ch == '\n' {
|
||||||
newLines++
|
newLines++
|
||||||
}
|
}
|
||||||
@@ -205,6 +279,11 @@ func Format(input []byte) []byte {
|
|||||||
write('{')
|
write('{')
|
||||||
openBraceWritten = true
|
openBraceWritten = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if spacePrior && ch == '<' {
|
||||||
|
space = true
|
||||||
|
}
|
||||||
|
|
||||||
write(ch)
|
write(ch)
|
||||||
|
|
||||||
beginningOfLine = false
|
beginningOfLine = false
|
||||||
|
|||||||
@@ -362,6 +362,76 @@ block {
|
|||||||
|
|
||||||
block {
|
block {
|
||||||
}
|
}
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
description: "keep heredoc as-is",
|
||||||
|
input: `block {
|
||||||
|
heredoc <<HEREDOC
|
||||||
|
Here's more than one space Here's more than one space
|
||||||
|
HEREDOC
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
expect: `block {
|
||||||
|
heredoc <<HEREDOC
|
||||||
|
Here's more than one space Here's more than one space
|
||||||
|
HEREDOC
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
description: "Mixing heredoc with regular part",
|
||||||
|
input: `block {
|
||||||
|
heredoc <<HEREDOC
|
||||||
|
Here's more than one space Here's more than one space
|
||||||
|
HEREDOC
|
||||||
|
respond "More than one space will be eaten" 200
|
||||||
|
}
|
||||||
|
|
||||||
|
block2 {
|
||||||
|
heredoc <<HEREDOC
|
||||||
|
Here's more than one space Here's more than one space
|
||||||
|
HEREDOC
|
||||||
|
respond "More than one space will be eaten" 200
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
expect: `block {
|
||||||
|
heredoc <<HEREDOC
|
||||||
|
Here's more than one space Here's more than one space
|
||||||
|
HEREDOC
|
||||||
|
respond "More than one space will be eaten" 200
|
||||||
|
}
|
||||||
|
|
||||||
|
block2 {
|
||||||
|
heredoc <<HEREDOC
|
||||||
|
Here's more than one space Here's more than one space
|
||||||
|
HEREDOC
|
||||||
|
respond "More than one space will be eaten" 200
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
description: "Heredoc as regular token",
|
||||||
|
input: `block {
|
||||||
|
heredoc <<HEREDOC "More than one space will be eaten"
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
expect: `block {
|
||||||
|
heredoc <<HEREDOC "More than one space will be eaten"
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
description: "Escape heredoc",
|
||||||
|
input: `block {
|
||||||
|
heredoc \<<HEREDOC
|
||||||
|
respond "More than one space will be eaten" 200
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
expect: `block {
|
||||||
|
heredoc \<<HEREDOC
|
||||||
|
respond "More than one space will be eaten" 200
|
||||||
|
}
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
} {
|
} {
|
||||||
|
|||||||
@@ -19,8 +19,9 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// parseVariadic determines if the token is a variadic placeholder,
|
// parseVariadic determines if the token is a variadic placeholder,
|
||||||
@@ -51,6 +52,13 @@ func parseVariadic(token Token, argCount int) (bool, int, int) {
|
|||||||
return false, 0, 0
|
return false, 0, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A valid token may contain several placeholders, and
|
||||||
|
// they may be separated by ":". It's not variadic.
|
||||||
|
// https://github.com/caddyserver/caddy/issues/5716
|
||||||
|
if strings.Contains(start, "}") || strings.Contains(end, "{") {
|
||||||
|
return false, 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
startIndex = 0
|
startIndex = 0
|
||||||
endIndex = argCount
|
endIndex = argCount
|
||||||
|
|||||||
@@ -16,24 +16,26 @@ package caddyfile
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
)
|
)
|
||||||
|
|
||||||
type adjacency map[string][]string
|
type adjacency map[string][]string
|
||||||
|
|
||||||
type importGraph struct {
|
type importGraph struct {
|
||||||
nodes map[string]bool
|
nodes map[string]struct{}
|
||||||
edges adjacency
|
edges adjacency
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *importGraph) addNode(name string) {
|
func (i *importGraph) addNode(name string) {
|
||||||
if i.nodes == nil {
|
if i.nodes == nil {
|
||||||
i.nodes = make(map[string]bool)
|
i.nodes = make(map[string]struct{})
|
||||||
}
|
}
|
||||||
if _, exists := i.nodes[name]; exists {
|
if _, exists := i.nodes[name]; exists {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
i.nodes[name] = true
|
i.nodes[name] = struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *importGraph) addNodes(names []string) {
|
func (i *importGraph) addNodes(names []string) {
|
||||||
for _, name := range names {
|
for _, name := range names {
|
||||||
i.addNode(name)
|
i.addNode(name)
|
||||||
@@ -43,6 +45,7 @@ func (i *importGraph) addNodes(names []string) {
|
|||||||
func (i *importGraph) removeNode(name string) {
|
func (i *importGraph) removeNode(name string) {
|
||||||
delete(i.nodes, name)
|
delete(i.nodes, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *importGraph) removeNodes(names []string) {
|
func (i *importGraph) removeNodes(names []string) {
|
||||||
for _, name := range names {
|
for _, name := range names {
|
||||||
i.removeNode(name)
|
i.removeNode(name)
|
||||||
@@ -64,7 +67,7 @@ func (i *importGraph) addEdge(from, to string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if i.nodes == nil {
|
if i.nodes == nil {
|
||||||
i.nodes = make(map[string]bool)
|
i.nodes = make(map[string]struct{})
|
||||||
}
|
}
|
||||||
if i.edges == nil {
|
if i.edges == nil {
|
||||||
i.edges = make(adjacency)
|
i.edges = make(adjacency)
|
||||||
@@ -73,6 +76,7 @@ func (i *importGraph) addEdge(from, to string) error {
|
|||||||
i.edges[from] = append(i.edges[from], to)
|
i.edges[from] = append(i.edges[from], to)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *importGraph) addEdges(from string, tos []string) error {
|
func (i *importGraph) addEdges(from string, tos []string) error {
|
||||||
for _, to := range tos {
|
for _, to := range tos {
|
||||||
err := i.addEdge(from, to)
|
err := i.addEdge(from, to)
|
||||||
@@ -88,12 +92,7 @@ func (i *importGraph) areConnected(from, to string) bool {
|
|||||||
if !ok {
|
if !ok {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for _, v := range al {
|
return slices.Contains(al, to)
|
||||||
if v == to {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *importGraph) willCycle(from, to string) bool {
|
func (i *importGraph) willCycle(from, to string) bool {
|
||||||
|
|||||||
@@ -137,18 +137,32 @@ func (l *lexer) next() (bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// detect whether we have the start of a heredoc
|
// detect whether we have the start of a heredoc
|
||||||
if !inHeredoc && !heredocEscaped && len(val) > 1 && string(val[:2]) == "<<" {
|
if !(quoted || btQuoted) && !(inHeredoc || heredocEscaped) &&
|
||||||
if ch == '<' {
|
len(val) > 1 && string(val[:2]) == "<<" {
|
||||||
return false, fmt.Errorf("too many '<' for heredoc on line #%d; only use two, for example <<END", l.line)
|
// a space means it's just a regular token and not a heredoc
|
||||||
|
if ch == ' ' {
|
||||||
|
return makeToken(0), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// skip CR, we only care about LF
|
||||||
if ch == '\r' {
|
if ch == '\r' {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// after hitting a newline, we know that the heredoc marker
|
// after hitting a newline, we know that the heredoc marker
|
||||||
// is the characters after the two << and the newline.
|
// is the characters after the two << and the newline.
|
||||||
// we reset the val because the heredoc is syntax we don't
|
// we reset the val because the heredoc is syntax we don't
|
||||||
// want to keep.
|
// want to keep.
|
||||||
if ch == '\n' {
|
if ch == '\n' {
|
||||||
|
if len(val) == 2 {
|
||||||
|
return false, fmt.Errorf("missing opening heredoc marker on line #%d; must contain only alpha-numeric characters, dashes and underscores; got empty string", l.line)
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if there's too many <
|
||||||
|
if string(val[:3]) == "<<<" {
|
||||||
|
return false, fmt.Errorf("too many '<' for heredoc on line #%d; only use two, for example <<END", l.line)
|
||||||
|
}
|
||||||
|
|
||||||
heredocMarker = string(val[2:])
|
heredocMarker = string(val[2:])
|
||||||
if !heredocMarkerRegexp.Match([]byte(heredocMarker)) {
|
if !heredocMarkerRegexp.Match([]byte(heredocMarker)) {
|
||||||
return false, fmt.Errorf("heredoc marker on line #%d must contain only alpha-numeric characters, dashes and underscores; got '%s'", l.line, heredocMarker)
|
return false, fmt.Errorf("heredoc marker on line #%d must contain only alpha-numeric characters, dashes and underscores; got '%s'", l.line, heredocMarker)
|
||||||
@@ -172,7 +186,7 @@ func (l *lexer) next() (bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// check if we're done, i.e. that the last few characters are the marker
|
// check if we're done, i.e. that the last few characters are the marker
|
||||||
if len(val) > len(heredocMarker) && heredocMarker == string(val[len(val)-len(heredocMarker):]) {
|
if len(val) >= len(heredocMarker) && heredocMarker == string(val[len(val)-len(heredocMarker):]) {
|
||||||
// set the final value
|
// set the final value
|
||||||
val, err = l.finalizeHeredoc(val, heredocMarker)
|
val, err = l.finalizeHeredoc(val, heredocMarker)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -299,6 +313,11 @@ func (l *lexer) finalizeHeredoc(val []rune, marker string) ([]rune, error) {
|
|||||||
// iterate over each line and strip the whitespace from the front
|
// iterate over each line and strip the whitespace from the front
|
||||||
var out string
|
var out string
|
||||||
for lineNum, lineText := range lines[:len(lines)-1] {
|
for lineNum, lineText := range lines[:len(lines)-1] {
|
||||||
|
if lineText == "" || lineText == "\r" {
|
||||||
|
out += "\n"
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
// find an exact match for the padding
|
// find an exact match for the padding
|
||||||
index := strings.Index(lineText, paddingToStrip)
|
index := strings.Index(lineText, paddingToStrip)
|
||||||
|
|
||||||
@@ -321,6 +340,8 @@ func (l *lexer) finalizeHeredoc(val []rune, marker string) ([]rune, error) {
|
|||||||
return []rune(out), nil
|
return []rune(out), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Quoted returns true if the token was enclosed in quotes
|
||||||
|
// (i.e. double quotes, backticks, or heredoc).
|
||||||
func (t Token) Quoted() bool {
|
func (t Token) Quoted() bool {
|
||||||
return t.wasQuoted > 0
|
return t.wasQuoted > 0
|
||||||
}
|
}
|
||||||
@@ -337,6 +358,19 @@ func (t Token) NumLineBreaks() int {
|
|||||||
return lineBreaks
|
return lineBreaks
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clone returns a deep copy of the token.
|
||||||
|
func (t Token) Clone() Token {
|
||||||
|
return Token{
|
||||||
|
File: t.File,
|
||||||
|
imports: append([]string{}, t.imports...),
|
||||||
|
Line: t.Line,
|
||||||
|
Text: t.Text,
|
||||||
|
wasQuoted: t.wasQuoted,
|
||||||
|
heredocMarker: t.heredocMarker,
|
||||||
|
snippetName: t.snippetName,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var heredocMarkerRegexp = regexp.MustCompile("^[A-Za-z0-9_-]+$")
|
var heredocMarkerRegexp = regexp.MustCompile("^[A-Za-z0-9_-]+$")
|
||||||
|
|
||||||
// isNextOnNewLine tests whether t2 is on a different line from t1
|
// isNextOnNewLine tests whether t2 is on a different line from t1
|
||||||
|
|||||||
@@ -285,6 +285,18 @@ EOF same-line-arg
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: []byte(`heredoc <<EOF
|
input: []byte(`heredoc <<EOF
|
||||||
|
EOF
|
||||||
|
HERE same-line-arg
|
||||||
|
`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: `heredoc`},
|
||||||
|
{Line: 1, Text: ``},
|
||||||
|
{Line: 3, Text: `HERE`},
|
||||||
|
{Line: 3, Text: `same-line-arg`},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`heredoc <<EOF
|
||||||
EOF same-line-arg
|
EOF same-line-arg
|
||||||
`),
|
`),
|
||||||
expected: []Token{
|
expected: []Token{
|
||||||
@@ -322,15 +334,59 @@ EOF same-line-arg
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: []byte(`heredoc <EOF
|
input: []byte(`escaped-heredoc \<< >>`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: `escaped-heredoc`},
|
||||||
|
{Line: 1, Text: `<<`},
|
||||||
|
{Line: 1, Text: `>>`},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`not-a-heredoc <EOF
|
||||||
content
|
content
|
||||||
EOF same-line-arg
|
|
||||||
`),
|
`),
|
||||||
expected: []Token{
|
expected: []Token{
|
||||||
{Line: 1, Text: `heredoc`},
|
{Line: 1, Text: `not-a-heredoc`},
|
||||||
{Line: 1, Text: `<EOF`},
|
{Line: 1, Text: `<EOF`},
|
||||||
{Line: 2, Text: `content`},
|
{Line: 2, Text: `content`},
|
||||||
{Line: 3, Text: `EOF`},
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`not-a-heredoc <<<EOF content`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: `not-a-heredoc`},
|
||||||
|
{Line: 1, Text: `<<<EOF`},
|
||||||
|
{Line: 1, Text: `content`},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`not-a-heredoc "<<" ">>"`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: `not-a-heredoc`},
|
||||||
|
{Line: 1, Text: `<<`},
|
||||||
|
{Line: 1, Text: `>>`},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`not-a-heredoc << >>`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: `not-a-heredoc`},
|
||||||
|
{Line: 1, Text: `<<`},
|
||||||
|
{Line: 1, Text: `>>`},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`not-a-heredoc <<HERE SAME LINE
|
||||||
|
content
|
||||||
|
HERE same-line-arg
|
||||||
|
`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: `not-a-heredoc`},
|
||||||
|
{Line: 1, Text: `<<HERE`},
|
||||||
|
{Line: 1, Text: `SAME`},
|
||||||
|
{Line: 1, Text: `LINE`},
|
||||||
|
{Line: 2, Text: `content`},
|
||||||
|
{Line: 3, Text: `HERE`},
|
||||||
{Line: 3, Text: `same-line-arg`},
|
{Line: 3, Text: `same-line-arg`},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -366,12 +422,9 @@ EOF same-line-arg
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: []byte(`heredoc <<HERE SAME LINE
|
input: []byte("not-a-heredoc <<\n"),
|
||||||
content
|
|
||||||
HERE same-line-arg
|
|
||||||
`),
|
|
||||||
expectErr: true,
|
expectErr: true,
|
||||||
errorMessage: "heredoc marker on line #1 must contain only alpha-numeric characters, dashes and underscores; got 'HERE SAME LINE'",
|
errorMessage: "missing opening heredoc marker on line #1; must contain only alpha-numeric characters, dashes and underscores; got empty string",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
input: []byte(`heredoc <<<EOF
|
input: []byte(`heredoc <<<EOF
|
||||||
@@ -404,6 +457,48 @@ EOF same-line-arg
|
|||||||
expectErr: true,
|
expectErr: true,
|
||||||
errorMessage: "mismatched leading whitespace in heredoc <<EOF on line #2 [ content], expected whitespace [\t\t] to match the closing marker",
|
errorMessage: "mismatched leading whitespace in heredoc <<EOF on line #2 [ content], expected whitespace [\t\t] to match the closing marker",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`heredoc <<EOF
|
||||||
|
The next line is a blank line
|
||||||
|
|
||||||
|
The previous line is a blank line
|
||||||
|
EOF`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: "heredoc"},
|
||||||
|
{Line: 1, Text: "The next line is a blank line\n\nThe previous line is a blank line"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`heredoc <<EOF
|
||||||
|
One tab indented heredoc with blank next line
|
||||||
|
|
||||||
|
One tab indented heredoc with blank previous line
|
||||||
|
EOF`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: "heredoc"},
|
||||||
|
{Line: 1, Text: "One tab indented heredoc with blank next line\n\nOne tab indented heredoc with blank previous line"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`heredoc <<EOF
|
||||||
|
The next line is a blank line with one tab
|
||||||
|
|
||||||
|
The previous line is a blank line with one tab
|
||||||
|
EOF`),
|
||||||
|
expected: []Token{
|
||||||
|
{Line: 1, Text: "heredoc"},
|
||||||
|
{Line: 1, Text: "The next line is a blank line with one tab\n\t\nThe previous line is a blank line with one tab"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
input: []byte(`heredoc <<EOF
|
||||||
|
The next line is a blank line with one tab less than the correct indentation
|
||||||
|
|
||||||
|
The previous line is a blank line with one tab less than the correct indentation
|
||||||
|
EOF`),
|
||||||
|
expectErr: true,
|
||||||
|
errorMessage: "mismatched leading whitespace in heredoc <<EOF on line #3 [\t], expected whitespace [\t\t] to match the closing marker",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, testCase := range testCases {
|
for i, testCase := range testCases {
|
||||||
|
|||||||
+110
-28
@@ -22,8 +22,9 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Parse parses the input just enough to group tokens, in
|
// Parse parses the input just enough to group tokens, in
|
||||||
@@ -49,7 +50,7 @@ func Parse(filename string, input []byte) ([]ServerBlock, error) {
|
|||||||
p := parser{
|
p := parser{
|
||||||
Dispenser: NewDispenser(tokens),
|
Dispenser: NewDispenser(tokens),
|
||||||
importGraph: importGraph{
|
importGraph: importGraph{
|
||||||
nodes: make(map[string]bool),
|
nodes: make(map[string]struct{}),
|
||||||
edges: make(adjacency),
|
edges: make(adjacency),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -159,14 +160,14 @@ func (p *parser) begin() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ok, name := p.isNamedRoute(); ok {
|
if ok, name := p.isNamedRoute(); ok {
|
||||||
// named routes only have one key, the route name
|
|
||||||
p.block.Keys = []string{name}
|
|
||||||
p.block.IsNamedRoute = true
|
|
||||||
|
|
||||||
// we just need a dummy leading token to ease parsing later
|
// we just need a dummy leading token to ease parsing later
|
||||||
nameToken := p.Token()
|
nameToken := p.Token()
|
||||||
nameToken.Text = name
|
nameToken.Text = name
|
||||||
|
|
||||||
|
// named routes only have one key, the route name
|
||||||
|
p.block.Keys = []Token{nameToken}
|
||||||
|
p.block.IsNamedRoute = true
|
||||||
|
|
||||||
// get all the tokens from the block, including the braces
|
// get all the tokens from the block, including the braces
|
||||||
tokens, err := p.blockTokens(true)
|
tokens, err := p.blockTokens(true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -210,10 +211,16 @@ func (p *parser) addresses() error {
|
|||||||
var expectingAnother bool
|
var expectingAnother bool
|
||||||
|
|
||||||
for {
|
for {
|
||||||
tkn := p.Val()
|
value := p.Val()
|
||||||
|
token := p.Token()
|
||||||
|
|
||||||
// special case: import directive replaces tokens during parse-time
|
// Reject request matchers if trying to define them globally
|
||||||
if tkn == "import" && p.isNewLine() {
|
if strings.HasPrefix(value, "@") {
|
||||||
|
return p.Errf("request matchers may not be defined globally, they must be in a site block; found %s", value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special case: import directive replaces tokens during parse-time
|
||||||
|
if value == "import" && p.isNewLine() {
|
||||||
err := p.doImport(0)
|
err := p.doImport(0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -222,9 +229,9 @@ func (p *parser) addresses() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Open brace definitely indicates end of addresses
|
// Open brace definitely indicates end of addresses
|
||||||
if tkn == "{" {
|
if value == "{" {
|
||||||
if expectingAnother {
|
if expectingAnother {
|
||||||
return p.Errf("Expected another address but had '%s' - check for extra comma", tkn)
|
return p.Errf("Expected another address but had '%s' - check for extra comma", value)
|
||||||
}
|
}
|
||||||
// Mark this server block as being defined with braces.
|
// Mark this server block as being defined with braces.
|
||||||
// This is used to provide a better error message when
|
// This is used to provide a better error message when
|
||||||
@@ -236,15 +243,15 @@ func (p *parser) addresses() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Users commonly forget to place a space between the address and the '{'
|
// Users commonly forget to place a space between the address and the '{'
|
||||||
if strings.HasSuffix(tkn, "{") {
|
if strings.HasSuffix(value, "{") {
|
||||||
return p.Errf("Site addresses cannot end with a curly brace: '%s' - put a space between the token and the brace", tkn)
|
return p.Errf("Site addresses cannot end with a curly brace: '%s' - put a space between the token and the brace", value)
|
||||||
}
|
}
|
||||||
|
|
||||||
if tkn != "" { // empty token possible if user typed ""
|
if value != "" { // empty token possible if user typed ""
|
||||||
// Trailing comma indicates another address will follow, which
|
// Trailing comma indicates another address will follow, which
|
||||||
// may possibly be on the next line
|
// may possibly be on the next line
|
||||||
if tkn[len(tkn)-1] == ',' {
|
if value[len(value)-1] == ',' {
|
||||||
tkn = tkn[:len(tkn)-1]
|
value = value[:len(value)-1]
|
||||||
expectingAnother = true
|
expectingAnother = true
|
||||||
} else {
|
} else {
|
||||||
expectingAnother = false // but we may still see another one on this line
|
expectingAnother = false // but we may still see another one on this line
|
||||||
@@ -253,11 +260,17 @@ func (p *parser) addresses() error {
|
|||||||
// If there's a comma here, it's probably because they didn't use a space
|
// If there's a comma here, it's probably because they didn't use a space
|
||||||
// between their two domains, e.g. "foo.com,bar.com", which would not be
|
// between their two domains, e.g. "foo.com,bar.com", which would not be
|
||||||
// parsed as two separate site addresses.
|
// parsed as two separate site addresses.
|
||||||
if strings.Contains(tkn, ",") {
|
if strings.Contains(value, ",") {
|
||||||
return p.Errf("Site addresses cannot contain a comma ',': '%s' - put a space after the comma to separate site addresses", tkn)
|
return p.Errf("Site addresses cannot contain a comma ',': '%s' - put a space after the comma to separate site addresses", value)
|
||||||
}
|
}
|
||||||
|
|
||||||
p.block.Keys = append(p.block.Keys, tkn)
|
// After the above, a comma surrounded by spaces would result
|
||||||
|
// in an empty token which we should ignore
|
||||||
|
if value != "" {
|
||||||
|
// Add the token as a site address
|
||||||
|
token.Text = value
|
||||||
|
p.block.Keys = append(p.block.Keys, token)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Advance token and possibly break out of loop or return error
|
// Advance token and possibly break out of loop or return error
|
||||||
@@ -356,9 +369,45 @@ func (p *parser) doImport(nesting int) error {
|
|||||||
// set up a replacer for non-variadic args replacement
|
// set up a replacer for non-variadic args replacement
|
||||||
repl := makeArgsReplacer(args)
|
repl := makeArgsReplacer(args)
|
||||||
|
|
||||||
|
// grab all the tokens (if it exists) from within a block that follows the import
|
||||||
|
var blockTokens []Token
|
||||||
|
for currentNesting := p.Nesting(); p.NextBlock(currentNesting); {
|
||||||
|
blockTokens = append(blockTokens, p.Token())
|
||||||
|
}
|
||||||
|
// initialize with size 1
|
||||||
|
blockMapping := make(map[string][]Token, 1)
|
||||||
|
if len(blockTokens) > 0 {
|
||||||
|
// use such tokens to create a new dispenser, and then use it to parse each block
|
||||||
|
bd := NewDispenser(blockTokens)
|
||||||
|
for bd.Next() {
|
||||||
|
// see if we can grab a key
|
||||||
|
var currentMappingKey string
|
||||||
|
if bd.Val() == "{" {
|
||||||
|
return p.Err("anonymous blocks are not supported")
|
||||||
|
}
|
||||||
|
currentMappingKey = bd.Val()
|
||||||
|
currentMappingTokens := []Token{}
|
||||||
|
// read all args until end of line / {
|
||||||
|
if bd.NextArg() {
|
||||||
|
currentMappingTokens = append(currentMappingTokens, bd.Token())
|
||||||
|
for bd.NextArg() {
|
||||||
|
currentMappingTokens = append(currentMappingTokens, bd.Token())
|
||||||
|
}
|
||||||
|
// TODO(elee1766): we don't enter another mapping here because it's annoying to extract the { and } properly.
|
||||||
|
// maybe someone can do that in the future
|
||||||
|
} else {
|
||||||
|
// attempt to enter a block and add tokens to the currentMappingTokens
|
||||||
|
for mappingNesting := bd.Nesting(); bd.NextBlock(mappingNesting); {
|
||||||
|
currentMappingTokens = append(currentMappingTokens, bd.Token())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blockMapping[currentMappingKey] = currentMappingTokens
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// splice out the import directive and its arguments
|
// splice out the import directive and its arguments
|
||||||
// (2 tokens, plus the length of args)
|
// (2 tokens, plus the length of args)
|
||||||
tokensBefore := p.tokens[:p.cursor-1-len(args)]
|
tokensBefore := p.tokens[:p.cursor-1-len(args)-len(blockTokens)]
|
||||||
tokensAfter := p.tokens[p.cursor+1:]
|
tokensAfter := p.tokens[p.cursor+1:]
|
||||||
var importedTokens []Token
|
var importedTokens []Token
|
||||||
var nodes []string
|
var nodes []string
|
||||||
@@ -392,7 +441,6 @@ func (p *parser) doImport(nesting int) error {
|
|||||||
return p.Errf("Glob pattern may only contain one wildcard (*), but has others: %s", globPattern)
|
return p.Errf("Glob pattern may only contain one wildcard (*), but has others: %s", globPattern)
|
||||||
}
|
}
|
||||||
matches, err = filepath.Glob(globPattern)
|
matches, err = filepath.Glob(globPattern)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return p.Errf("Failed to use import pattern %s: %v", importPattern, err)
|
return p.Errf("Failed to use import pattern %s: %v", importPattern, err)
|
||||||
}
|
}
|
||||||
@@ -488,6 +536,33 @@ func (p *parser) doImport(nesting int) error {
|
|||||||
maybeSnippet = false
|
maybeSnippet = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// if it is {block}, we substitute with all tokens in the block
|
||||||
|
// if it is {blocks.*}, we substitute with the tokens in the mapping for the *
|
||||||
|
var skip bool
|
||||||
|
var tokensToAdd []Token
|
||||||
|
switch {
|
||||||
|
case token.Text == "{block}":
|
||||||
|
tokensToAdd = blockTokens
|
||||||
|
case strings.HasPrefix(token.Text, "{blocks.") && strings.HasSuffix(token.Text, "}"):
|
||||||
|
// {blocks.foo.bar} will be extracted to key `foo.bar`
|
||||||
|
blockKey := strings.TrimPrefix(strings.TrimSuffix(token.Text, "}"), "{blocks.")
|
||||||
|
val, ok := blockMapping[blockKey]
|
||||||
|
if ok {
|
||||||
|
tokensToAdd = val
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
skip = true
|
||||||
|
}
|
||||||
|
if !skip {
|
||||||
|
if len(tokensToAdd) == 0 {
|
||||||
|
// if there is no content in the snippet block, don't do any replacement
|
||||||
|
// this allows snippets which contained {block}/{block.*} before this change to continue functioning as normal
|
||||||
|
tokensCopy = append(tokensCopy, token)
|
||||||
|
} else {
|
||||||
|
tokensCopy = append(tokensCopy, tokensToAdd...)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if maybeSnippet {
|
if maybeSnippet {
|
||||||
tokensCopy = append(tokensCopy, token)
|
tokensCopy = append(tokensCopy, token)
|
||||||
@@ -509,7 +584,7 @@ func (p *parser) doImport(nesting int) error {
|
|||||||
// splice the imported tokens in the place of the import statement
|
// splice the imported tokens in the place of the import statement
|
||||||
// and rewind cursor so Next() will land on first imported token
|
// and rewind cursor so Next() will land on first imported token
|
||||||
p.tokens = append(tokensBefore, append(tokensCopy, tokensAfter...)...)
|
p.tokens = append(tokensBefore, append(tokensCopy, tokensAfter...)...)
|
||||||
p.cursor -= len(args) + 1
|
p.cursor -= len(args) + len(blockTokens) + 1
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -565,7 +640,6 @@ func (p *parser) doSingleImport(importFile string) ([]Token, error) {
|
|||||||
// are loaded into the current server block for later use
|
// are loaded into the current server block for later use
|
||||||
// by directive setup functions.
|
// by directive setup functions.
|
||||||
func (p *parser) directive() error {
|
func (p *parser) directive() error {
|
||||||
|
|
||||||
// a segment is a list of tokens associated with this directive
|
// a segment is a list of tokens associated with this directive
|
||||||
var segment Segment
|
var segment Segment
|
||||||
|
|
||||||
@@ -637,8 +711,8 @@ func (p *parser) closeCurlyBrace() error {
|
|||||||
func (p *parser) isNamedRoute() (bool, string) {
|
func (p *parser) isNamedRoute() (bool, string) {
|
||||||
keys := p.block.Keys
|
keys := p.block.Keys
|
||||||
// A named route block is a single key with parens, prefixed with &.
|
// A named route block is a single key with parens, prefixed with &.
|
||||||
if len(keys) == 1 && strings.HasPrefix(keys[0], "&(") && strings.HasSuffix(keys[0], ")") {
|
if len(keys) == 1 && strings.HasPrefix(keys[0].Text, "&(") && strings.HasSuffix(keys[0].Text, ")") {
|
||||||
return true, strings.TrimSuffix(keys[0][2:], ")")
|
return true, strings.TrimSuffix(keys[0].Text[2:], ")")
|
||||||
}
|
}
|
||||||
return false, ""
|
return false, ""
|
||||||
}
|
}
|
||||||
@@ -646,8 +720,8 @@ func (p *parser) isNamedRoute() (bool, string) {
|
|||||||
func (p *parser) isSnippet() (bool, string) {
|
func (p *parser) isSnippet() (bool, string) {
|
||||||
keys := p.block.Keys
|
keys := p.block.Keys
|
||||||
// A snippet block is a single key with parens. Nothing else qualifies.
|
// A snippet block is a single key with parens. Nothing else qualifies.
|
||||||
if len(keys) == 1 && strings.HasPrefix(keys[0], "(") && strings.HasSuffix(keys[0], ")") {
|
if len(keys) == 1 && strings.HasPrefix(keys[0].Text, "(") && strings.HasSuffix(keys[0].Text, ")") {
|
||||||
return true, strings.TrimSuffix(keys[0][1:], ")")
|
return true, strings.TrimSuffix(keys[0].Text[1:], ")")
|
||||||
}
|
}
|
||||||
return false, ""
|
return false, ""
|
||||||
}
|
}
|
||||||
@@ -691,11 +765,19 @@ func (p *parser) blockTokens(retainCurlies bool) ([]Token, error) {
|
|||||||
// grouped by segments.
|
// grouped by segments.
|
||||||
type ServerBlock struct {
|
type ServerBlock struct {
|
||||||
HasBraces bool
|
HasBraces bool
|
||||||
Keys []string
|
Keys []Token
|
||||||
Segments []Segment
|
Segments []Segment
|
||||||
IsNamedRoute bool
|
IsNamedRoute bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (sb ServerBlock) GetKeysText() []string {
|
||||||
|
res := []string{}
|
||||||
|
for _, k := range sb.Keys {
|
||||||
|
res = append(res, k.Text)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
// DispenseDirective returns a dispenser that contains
|
// DispenseDirective returns a dispenser that contains
|
||||||
// all the tokens in the server block.
|
// all the tokens in the server block.
|
||||||
func (sb ServerBlock) DispenseDirective(dir string) *Dispenser {
|
func (sb ServerBlock) DispenseDirective(dir string) *Dispenser {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestParseVariadic(t *testing.T) {
|
func TestParseVariadic(t *testing.T) {
|
||||||
var args = make([]string, 10)
|
args := make([]string, 10)
|
||||||
for i, tc := range []struct {
|
for i, tc := range []struct {
|
||||||
input string
|
input string
|
||||||
result bool
|
result bool
|
||||||
@@ -91,6 +91,10 @@ func TestParseVariadic(t *testing.T) {
|
|||||||
input: "{args[0:10]}",
|
input: "{args[0:10]}",
|
||||||
result: true,
|
result: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
input: "{args[0]}:{args[1]}:{args[2]}",
|
||||||
|
result: false,
|
||||||
|
},
|
||||||
} {
|
} {
|
||||||
token := Token{
|
token := Token{
|
||||||
File: "test",
|
File: "test",
|
||||||
@@ -107,7 +111,6 @@ func TestAllTokens(t *testing.T) {
|
|||||||
input := []byte("a b c\nd e")
|
input := []byte("a b c\nd e")
|
||||||
expected := []string{"a", "b", "c", "d", "e"}
|
expected := []string{"a", "b", "c", "d", "e"}
|
||||||
tokens, err := allTokens("TestAllTokens", input)
|
tokens, err := allTokens("TestAllTokens", input)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Expected no error, got %v", err)
|
t.Fatalf("Expected no error, got %v", err)
|
||||||
}
|
}
|
||||||
@@ -145,7 +148,8 @@ func TestParseOneAndImport(t *testing.T) {
|
|||||||
"localhost",
|
"localhost",
|
||||||
}, []int{1}},
|
}, []int{1}},
|
||||||
|
|
||||||
{`localhost:1234
|
{
|
||||||
|
`localhost:1234
|
||||||
dir1 foo bar`, false, []string{
|
dir1 foo bar`, false, []string{
|
||||||
"localhost:1234",
|
"localhost:1234",
|
||||||
}, []int{3},
|
}, []int{3},
|
||||||
@@ -343,7 +347,7 @@ func TestParseOneAndImport(t *testing.T) {
|
|||||||
i, len(test.keys), len(result.Keys))
|
i, len(test.keys), len(result.Keys))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for j, addr := range result.Keys {
|
for j, addr := range result.GetKeysText() {
|
||||||
if addr != test.keys[j] {
|
if addr != test.keys[j] {
|
||||||
t.Errorf("Test %d, key %d: Expected '%s', but was '%s'",
|
t.Errorf("Test %d, key %d: Expected '%s', but was '%s'",
|
||||||
i, j, test.keys[j], addr)
|
i, j, test.keys[j], addr)
|
||||||
@@ -375,8 +379,9 @@ func TestRecursiveImport(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isExpected := func(got ServerBlock) bool {
|
isExpected := func(got ServerBlock) bool {
|
||||||
if len(got.Keys) != 1 || got.Keys[0] != "localhost" {
|
textKeys := got.GetKeysText()
|
||||||
t.Errorf("got keys unexpected: expect localhost, got %v", got.Keys)
|
if len(textKeys) != 1 || textKeys[0] != "localhost" {
|
||||||
|
t.Errorf("got keys unexpected: expect localhost, got %v", textKeys)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if len(got.Segments) != 2 {
|
if len(got.Segments) != 2 {
|
||||||
@@ -403,13 +408,13 @@ func TestRecursiveImport(t *testing.T) {
|
|||||||
err = os.WriteFile(recursiveFile1, []byte(
|
err = os.WriteFile(recursiveFile1, []byte(
|
||||||
`localhost
|
`localhost
|
||||||
dir1
|
dir1
|
||||||
import recursive_import_test2`), 0644)
|
import recursive_import_test2`), 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer os.Remove(recursiveFile1)
|
defer os.Remove(recursiveFile1)
|
||||||
|
|
||||||
err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0644)
|
err = os.WriteFile(recursiveFile2, []byte("dir2 1"), 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -437,7 +442,7 @@ func TestRecursiveImport(t *testing.T) {
|
|||||||
err = os.WriteFile(recursiveFile1, []byte(
|
err = os.WriteFile(recursiveFile1, []byte(
|
||||||
`localhost
|
`localhost
|
||||||
dir1
|
dir1
|
||||||
import `+recursiveFile2), 0644)
|
import `+recursiveFile2), 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -470,8 +475,9 @@ func TestDirectiveImport(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isExpected := func(got ServerBlock) bool {
|
isExpected := func(got ServerBlock) bool {
|
||||||
if len(got.Keys) != 1 || got.Keys[0] != "localhost" {
|
textKeys := got.GetKeysText()
|
||||||
t.Errorf("got keys unexpected: expect localhost, got %v", got.Keys)
|
if len(textKeys) != 1 || textKeys[0] != "localhost" {
|
||||||
|
t.Errorf("got keys unexpected: expect localhost, got %v", textKeys)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if len(got.Segments) != 2 {
|
if len(got.Segments) != 2 {
|
||||||
@@ -491,7 +497,7 @@ func TestDirectiveImport(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = os.WriteFile(directiveFile, []byte(`prop1 1
|
err = os.WriteFile(directiveFile, []byte(`prop1 1
|
||||||
prop2 2`), 0644)
|
prop2 2`), 0o644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -549,6 +555,10 @@ func TestParseAll(t *testing.T) {
|
|||||||
{"localhost:1234", "http://host2"},
|
{"localhost:1234", "http://host2"},
|
||||||
}},
|
}},
|
||||||
|
|
||||||
|
{`foo.example.com , example.com`, false, [][]string{
|
||||||
|
{"foo.example.com", "example.com"},
|
||||||
|
}},
|
||||||
|
|
||||||
{`localhost:1234, http://host2,`, true, [][]string{}},
|
{`localhost:1234, http://host2,`, true, [][]string{}},
|
||||||
|
|
||||||
{`http://host1.com, http://host2.com {
|
{`http://host1.com, http://host2.com {
|
||||||
@@ -608,11 +618,11 @@ func TestParseAll(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for j, block := range blocks {
|
for j, block := range blocks {
|
||||||
if len(block.Keys) != len(test.keys[j]) {
|
if len(block.Keys) != len(test.keys[j]) {
|
||||||
t.Errorf("Test %d: Expected %d keys in block %d, got %d",
|
t.Errorf("Test %d: Expected %d keys in block %d, got %d: %v",
|
||||||
i, len(test.keys[j]), j, len(block.Keys))
|
i, len(test.keys[j]), j, len(block.Keys), block.Keys)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for k, addr := range block.Keys {
|
for k, addr := range block.GetKeysText() {
|
||||||
if addr != test.keys[j][k] {
|
if addr != test.keys[j][k] {
|
||||||
t.Errorf("Test %d, block %d, key %d: Expected '%s', but got '%s'",
|
t.Errorf("Test %d, block %d, key %d: Expected '%s', but got '%s'",
|
||||||
i, j, k, test.keys[j][k], addr)
|
i, j, k, test.keys[j][k], addr)
|
||||||
@@ -765,7 +775,7 @@ func TestSnippets(t *testing.T) {
|
|||||||
if len(blocks) != 1 {
|
if len(blocks) != 1 {
|
||||||
t.Fatalf("Expect exactly one server block. Got %d.", len(blocks))
|
t.Fatalf("Expect exactly one server block. Got %d.", len(blocks))
|
||||||
}
|
}
|
||||||
if actual, expected := blocks[0].Keys[0], "http://example.com"; expected != actual {
|
if actual, expected := blocks[0].GetKeysText()[0], "http://example.com"; expected != actual {
|
||||||
t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual)
|
t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual)
|
||||||
}
|
}
|
||||||
if len(blocks[0].Segments) != 2 {
|
if len(blocks[0].Segments) != 2 {
|
||||||
@@ -797,7 +807,7 @@ func TestImportedFilesIgnoreNonDirectiveImportTokens(t *testing.T) {
|
|||||||
fileName := writeStringToTempFileOrDie(t, `
|
fileName := writeStringToTempFileOrDie(t, `
|
||||||
http://example.com {
|
http://example.com {
|
||||||
# This isn't an import directive, it's just an arg with value 'import'
|
# This isn't an import directive, it's just an arg with value 'import'
|
||||||
basicauth / import password
|
basic_auth / import password
|
||||||
}
|
}
|
||||||
`)
|
`)
|
||||||
// Parse the root file that imports the other one.
|
// Parse the root file that imports the other one.
|
||||||
@@ -808,12 +818,12 @@ func TestImportedFilesIgnoreNonDirectiveImportTokens(t *testing.T) {
|
|||||||
}
|
}
|
||||||
auth := blocks[0].Segments[0]
|
auth := blocks[0].Segments[0]
|
||||||
line := auth[0].Text + " " + auth[1].Text + " " + auth[2].Text + " " + auth[3].Text
|
line := auth[0].Text + " " + auth[1].Text + " " + auth[2].Text + " " + auth[3].Text
|
||||||
if line != "basicauth / import password" {
|
if line != "basic_auth / import password" {
|
||||||
// Previously, it would be changed to:
|
// Previously, it would be changed to:
|
||||||
// basicauth / import /path/to/test/dir/password
|
// basic_auth / import /path/to/test/dir/password
|
||||||
// referencing a file that (probably) doesn't exist and changing the
|
// referencing a file that (probably) doesn't exist and changing the
|
||||||
// password!
|
// password!
|
||||||
t.Errorf("Expected basicauth tokens to be 'basicauth / import password' but got %#q", line)
|
t.Errorf("Expected basic_auth tokens to be 'basic_auth / import password' but got %#q", line)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -840,7 +850,7 @@ func TestSnippetAcrossMultipleFiles(t *testing.T) {
|
|||||||
if len(blocks) != 1 {
|
if len(blocks) != 1 {
|
||||||
t.Fatalf("Expect exactly one server block. Got %d.", len(blocks))
|
t.Fatalf("Expect exactly one server block. Got %d.", len(blocks))
|
||||||
}
|
}
|
||||||
if actual, expected := blocks[0].Keys[0], "http://example.com"; expected != actual {
|
if actual, expected := blocks[0].GetKeysText()[0], "http://example.com"; expected != actual {
|
||||||
t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual)
|
t.Errorf("Expected server name to be '%s' but was '%s'", expected, actual)
|
||||||
}
|
}
|
||||||
if len(blocks[0].Segments) != 1 {
|
if len(blocks[0].Segments) != 1 {
|
||||||
@@ -851,6 +861,29 @@ func TestSnippetAcrossMultipleFiles(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRejectsGlobalMatcher(t *testing.T) {
|
||||||
|
p := testParser(`
|
||||||
|
@rejected path /foo
|
||||||
|
|
||||||
|
(common) {
|
||||||
|
gzip foo
|
||||||
|
errors stderr
|
||||||
|
}
|
||||||
|
|
||||||
|
http://example.com {
|
||||||
|
import common
|
||||||
|
}
|
||||||
|
`)
|
||||||
|
_, err := p.parseAll()
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Expected an error, but got nil")
|
||||||
|
}
|
||||||
|
expected := "request matchers may not be defined globally, they must be in a site block; found @rejected, at Testfile:2"
|
||||||
|
if err.Error() != expected {
|
||||||
|
t.Errorf("Expected error to be '%s' but got '%v'", expected, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func testParser(input string) parser {
|
func testParser(input string) parser {
|
||||||
return parser{Dispenser: NewTestDispenser(input)}
|
return parser{Dispenser: NewTestDispenser(input)}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,11 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
|
"github.com/caddyserver/certmagic"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
"github.com/caddyserver/caddy/v2"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/caddyserver/certmagic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// mapAddressToServerBlocks returns a map of listener address to list of server
|
// mapAddressToServerBlocks returns a map of listener address to list of server
|
||||||
@@ -76,9 +77,15 @@ import (
|
|||||||
// repetition may be undesirable, so call consolidateAddrMappings() to map
|
// repetition may be undesirable, so call consolidateAddrMappings() to map
|
||||||
// multiple addresses to the same lists of server blocks (a many:many mapping).
|
// multiple addresses to the same lists of server blocks (a many:many mapping).
|
||||||
// (Doing this is essentially a map-reduce technique.)
|
// (Doing this is essentially a map-reduce technique.)
|
||||||
func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBlock,
|
func (st *ServerType) mapAddressToProtocolToServerBlocks(originalServerBlocks []serverBlock,
|
||||||
options map[string]any) (map[string][]serverBlock, error) {
|
options map[string]any,
|
||||||
sbmap := make(map[string][]serverBlock)
|
) (map[string]map[string][]serverBlock, error) {
|
||||||
|
addrToProtocolToServerBlocks := map[string]map[string][]serverBlock{}
|
||||||
|
|
||||||
|
type keyWithParsedKey struct {
|
||||||
|
key caddyfile.Token
|
||||||
|
parsedKey Address
|
||||||
|
}
|
||||||
|
|
||||||
for i, sblock := range originalServerBlocks {
|
for i, sblock := range originalServerBlocks {
|
||||||
// within a server block, we need to map all the listener addresses
|
// within a server block, we need to map all the listener addresses
|
||||||
@@ -86,27 +93,48 @@ func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBloc
|
|||||||
// will be served by them; this has the effect of treating each
|
// will be served by them; this has the effect of treating each
|
||||||
// key of a server block as its own, but without having to repeat its
|
// key of a server block as its own, but without having to repeat its
|
||||||
// contents in cases where multiple keys really can be served together
|
// contents in cases where multiple keys really can be served together
|
||||||
addrToKeys := make(map[string][]string)
|
addrToProtocolToKeyWithParsedKeys := map[string]map[string][]keyWithParsedKey{}
|
||||||
for j, key := range sblock.block.Keys {
|
for j, key := range sblock.block.Keys {
|
||||||
|
parsedKey, err := ParseAddress(key.Text)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parsing key: %v", err)
|
||||||
|
}
|
||||||
|
parsedKey = parsedKey.Normalize()
|
||||||
|
|
||||||
// a key can have multiple listener addresses if there are multiple
|
// a key can have multiple listener addresses if there are multiple
|
||||||
// arguments to the 'bind' directive (although they will all have
|
// arguments to the 'bind' directive (although they will all have
|
||||||
// the same port, since the port is defined by the key or is implicit
|
// the same port, since the port is defined by the key or is implicit
|
||||||
// through automatic HTTPS)
|
// through automatic HTTPS)
|
||||||
addrs, err := st.listenerAddrsForServerBlockKey(sblock, key, options)
|
listeners, err := st.listenersForServerBlockAddress(sblock, parsedKey, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("server block %d, key %d (%s): determining listener address: %v", i, j, key, err)
|
return nil, fmt.Errorf("server block %d, key %d (%s): determining listener address: %v", i, j, key.Text, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// associate this key with each listener address it is served on
|
// associate this key with its protocols and each listener address served with them
|
||||||
for _, addr := range addrs {
|
kwpk := keyWithParsedKey{key, parsedKey}
|
||||||
addrToKeys[addr] = append(addrToKeys[addr], key)
|
for addr, protocols := range listeners {
|
||||||
|
protocolToKeyWithParsedKeys, ok := addrToProtocolToKeyWithParsedKeys[addr]
|
||||||
|
if !ok {
|
||||||
|
protocolToKeyWithParsedKeys = map[string][]keyWithParsedKey{}
|
||||||
|
addrToProtocolToKeyWithParsedKeys[addr] = protocolToKeyWithParsedKeys
|
||||||
|
}
|
||||||
|
|
||||||
|
// an empty protocol indicates the default, a nil or empty value in the ListenProtocols array
|
||||||
|
if len(protocols) == 0 {
|
||||||
|
protocols[""] = struct{}{}
|
||||||
|
}
|
||||||
|
for prot := range protocols {
|
||||||
|
protocolToKeyWithParsedKeys[prot] = append(
|
||||||
|
protocolToKeyWithParsedKeys[prot],
|
||||||
|
kwpk)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// make a slice of the map keys so we can iterate in sorted order
|
// make a slice of the map keys so we can iterate in sorted order
|
||||||
addrs := make([]string, 0, len(addrToKeys))
|
addrs := make([]string, 0, len(addrToProtocolToKeyWithParsedKeys))
|
||||||
for k := range addrToKeys {
|
for addr := range addrToProtocolToKeyWithParsedKeys {
|
||||||
addrs = append(addrs, k)
|
addrs = append(addrs, addr)
|
||||||
}
|
}
|
||||||
sort.Strings(addrs)
|
sort.Strings(addrs)
|
||||||
|
|
||||||
@@ -116,83 +144,142 @@ func (st *ServerType) mapAddressToServerBlocks(originalServerBlocks []serverBloc
|
|||||||
// server block are only the ones which use the address; but
|
// server block are only the ones which use the address; but
|
||||||
// the contents (tokens) are of course the same
|
// the contents (tokens) are of course the same
|
||||||
for _, addr := range addrs {
|
for _, addr := range addrs {
|
||||||
keys := addrToKeys[addr]
|
protocolToKeyWithParsedKeys := addrToProtocolToKeyWithParsedKeys[addr]
|
||||||
// parse keys so that we only have to do it once
|
|
||||||
parsedKeys := make([]Address, 0, len(keys))
|
prots := make([]string, 0, len(protocolToKeyWithParsedKeys))
|
||||||
for _, key := range keys {
|
for prot := range protocolToKeyWithParsedKeys {
|
||||||
addr, err := ParseAddress(key)
|
prots = append(prots, prot)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("parsing key '%s': %v", key, err)
|
|
||||||
}
|
}
|
||||||
parsedKeys = append(parsedKeys, addr.Normalize())
|
sort.Strings(prots)
|
||||||
|
|
||||||
|
protocolToServerBlocks, ok := addrToProtocolToServerBlocks[addr]
|
||||||
|
if !ok {
|
||||||
|
protocolToServerBlocks = map[string][]serverBlock{}
|
||||||
|
addrToProtocolToServerBlocks[addr] = protocolToServerBlocks
|
||||||
}
|
}
|
||||||
sbmap[addr] = append(sbmap[addr], serverBlock{
|
|
||||||
|
for _, prot := range prots {
|
||||||
|
keyWithParsedKeys := protocolToKeyWithParsedKeys[prot]
|
||||||
|
|
||||||
|
keys := make([]caddyfile.Token, len(keyWithParsedKeys))
|
||||||
|
parsedKeys := make([]Address, len(keyWithParsedKeys))
|
||||||
|
|
||||||
|
for k, keyWithParsedKey := range keyWithParsedKeys {
|
||||||
|
keys[k] = keyWithParsedKey.key
|
||||||
|
parsedKeys[k] = keyWithParsedKey.parsedKey
|
||||||
|
}
|
||||||
|
|
||||||
|
protocolToServerBlocks[prot] = append(protocolToServerBlocks[prot], serverBlock{
|
||||||
block: caddyfile.ServerBlock{
|
block: caddyfile.ServerBlock{
|
||||||
Keys: keys,
|
Keys: keys,
|
||||||
Segments: sblock.block.Segments,
|
Segments: sblock.block.Segments,
|
||||||
},
|
},
|
||||||
pile: sblock.pile,
|
pile: sblock.pile,
|
||||||
keys: parsedKeys,
|
parsedKeys: parsedKeys,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return sbmap, nil
|
return addrToProtocolToServerBlocks, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// consolidateAddrMappings eliminates repetition of identical server blocks in a mapping of
|
// consolidateAddrMappings eliminates repetition of identical server blocks in a mapping of
|
||||||
// single listener addresses to lists of server blocks. Since multiple addresses may serve
|
// single listener addresses to protocols to lists of server blocks. Since multiple addresses
|
||||||
// identical sites (server block contents), this function turns a 1:many mapping into a
|
// may serve multiple protocols to identical sites (server block contents), this function turns
|
||||||
// many:many mapping. Server block contents (tokens) must be exactly identical so that
|
// a 1:many mapping into a many:many mapping. Server block contents (tokens) must be
|
||||||
// reflect.DeepEqual returns true in order for the addresses to be combined. Identical
|
// exactly identical so that reflect.DeepEqual returns true in order for the addresses to be combined.
|
||||||
// entries are deleted from the addrToServerBlocks map. Essentially, each pairing (each
|
// Identical entries are deleted from the addrToServerBlocks map. Essentially, each pairing (each
|
||||||
// association from multiple addresses to multiple server blocks; i.e. each element of
|
// association from multiple addresses to multiple server blocks; i.e. each element of
|
||||||
// the returned slice) becomes a server definition in the output JSON.
|
// the returned slice) becomes a server definition in the output JSON.
|
||||||
func (st *ServerType) consolidateAddrMappings(addrToServerBlocks map[string][]serverBlock) []sbAddrAssociation {
|
func (st *ServerType) consolidateAddrMappings(addrToProtocolToServerBlocks map[string]map[string][]serverBlock) []sbAddrAssociation {
|
||||||
sbaddrs := make([]sbAddrAssociation, 0, len(addrToServerBlocks))
|
sbaddrs := make([]sbAddrAssociation, 0, len(addrToProtocolToServerBlocks))
|
||||||
for addr, sblocks := range addrToServerBlocks {
|
|
||||||
// we start with knowing that at least this address
|
addrs := make([]string, 0, len(addrToProtocolToServerBlocks))
|
||||||
// maps to these server blocks
|
for addr := range addrToProtocolToServerBlocks {
|
||||||
a := sbAddrAssociation{
|
addrs = append(addrs, addr)
|
||||||
addresses: []string{addr},
|
|
||||||
serverBlocks: sblocks,
|
|
||||||
}
|
}
|
||||||
|
sort.Strings(addrs)
|
||||||
|
|
||||||
|
for _, addr := range addrs {
|
||||||
|
protocolToServerBlocks := addrToProtocolToServerBlocks[addr]
|
||||||
|
|
||||||
|
prots := make([]string, 0, len(protocolToServerBlocks))
|
||||||
|
for prot := range protocolToServerBlocks {
|
||||||
|
prots = append(prots, prot)
|
||||||
|
}
|
||||||
|
sort.Strings(prots)
|
||||||
|
|
||||||
|
for _, prot := range prots {
|
||||||
|
serverBlocks := protocolToServerBlocks[prot]
|
||||||
|
|
||||||
// now find other addresses that map to identical
|
// now find other addresses that map to identical
|
||||||
// server blocks and add them to our list of
|
// server blocks and add them to our map of listener
|
||||||
// addresses, while removing them from the map
|
// addresses and protocols, while removing them from
|
||||||
for otherAddr, otherSblocks := range addrToServerBlocks {
|
// the original map
|
||||||
if addr == otherAddr {
|
listeners := map[string]map[string]struct{}{}
|
||||||
continue
|
|
||||||
}
|
|
||||||
if reflect.DeepEqual(sblocks, otherSblocks) {
|
|
||||||
a.addresses = append(a.addresses, otherAddr)
|
|
||||||
delete(addrToServerBlocks, otherAddr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Strings(a.addresses)
|
|
||||||
|
|
||||||
sbaddrs = append(sbaddrs, a)
|
for otherAddr, otherProtocolToServerBlocks := range addrToProtocolToServerBlocks {
|
||||||
|
for otherProt, otherServerBlocks := range otherProtocolToServerBlocks {
|
||||||
|
if addr == otherAddr && prot == otherProt || reflect.DeepEqual(serverBlocks, otherServerBlocks) {
|
||||||
|
listener, ok := listeners[otherAddr]
|
||||||
|
if !ok {
|
||||||
|
listener = map[string]struct{}{}
|
||||||
|
listeners[otherAddr] = listener
|
||||||
|
}
|
||||||
|
listener[otherProt] = struct{}{}
|
||||||
|
delete(otherProtocolToServerBlocks, otherProt)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// sort them by their first address (we know there will always be at least one)
|
addresses := make([]string, 0, len(listeners))
|
||||||
// to avoid problems with non-deterministic ordering (makes tests flaky)
|
for lnAddr := range listeners {
|
||||||
sort.Slice(sbaddrs, func(i, j int) bool {
|
addresses = append(addresses, lnAddr)
|
||||||
return sbaddrs[i].addresses[0] < sbaddrs[j].addresses[0]
|
}
|
||||||
|
sort.Strings(addresses)
|
||||||
|
|
||||||
|
addressesWithProtocols := make([]addressWithProtocols, 0, len(listeners))
|
||||||
|
|
||||||
|
for _, lnAddr := range addresses {
|
||||||
|
lnProts := listeners[lnAddr]
|
||||||
|
prots := make([]string, 0, len(lnProts))
|
||||||
|
for prot := range lnProts {
|
||||||
|
prots = append(prots, prot)
|
||||||
|
}
|
||||||
|
sort.Strings(prots)
|
||||||
|
|
||||||
|
addressesWithProtocols = append(addressesWithProtocols, addressWithProtocols{
|
||||||
|
address: lnAddr,
|
||||||
|
protocols: prots,
|
||||||
})
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
sbaddrs = append(sbaddrs, sbAddrAssociation{
|
||||||
|
addressesWithProtocols: addressesWithProtocols,
|
||||||
|
serverBlocks: serverBlocks,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return sbaddrs
|
return sbaddrs
|
||||||
}
|
}
|
||||||
|
|
||||||
// listenerAddrsForServerBlockKey essentially converts the Caddyfile
|
// listenersForServerBlockAddress essentially converts the Caddyfile site addresses to a map from
|
||||||
// site addresses to Caddy listener addresses for each server block.
|
// Caddy listener addresses and the protocols to serve them with to the parsed address for each server block.
|
||||||
func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key string,
|
func (st *ServerType) listenersForServerBlockAddress(sblock serverBlock, addr Address,
|
||||||
options map[string]any) ([]string, error) {
|
options map[string]any,
|
||||||
addr, err := ParseAddress(key)
|
) (map[string]map[string]struct{}, error) {
|
||||||
if err != nil {
|
switch addr.Scheme {
|
||||||
return nil, fmt.Errorf("parsing key: %v", err)
|
case "wss":
|
||||||
|
return nil, fmt.Errorf("the scheme wss:// is only supported in browsers; use https:// instead")
|
||||||
|
case "ws":
|
||||||
|
return nil, fmt.Errorf("the scheme ws:// is only supported in browsers; use http:// instead")
|
||||||
|
case "https", "http", "":
|
||||||
|
// Do nothing or handle the valid schemes
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported URL scheme %s://", addr.Scheme)
|
||||||
}
|
}
|
||||||
addr = addr.Normalize()
|
|
||||||
|
|
||||||
// figure out the HTTP and HTTPS ports; either
|
// figure out the HTTP and HTTPS ports; either
|
||||||
// use defaults, or override with user config
|
// use defaults, or override with user config
|
||||||
@@ -216,55 +303,54 @@ func (st *ServerType) listenerAddrsForServerBlockKey(sblock serverBlock, key str
|
|||||||
|
|
||||||
// error if scheme and port combination violate convention
|
// error if scheme and port combination violate convention
|
||||||
if (addr.Scheme == "http" && lnPort == httpsPort) || (addr.Scheme == "https" && lnPort == httpPort) {
|
if (addr.Scheme == "http" && lnPort == httpsPort) || (addr.Scheme == "https" && lnPort == httpPort) {
|
||||||
return nil, fmt.Errorf("[%s] scheme and port violate convention", key)
|
return nil, fmt.Errorf("[%s] scheme and port violate convention", addr.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
// the bind directive specifies hosts (and potentially network), but is optional
|
// the bind directive specifies hosts (and potentially network), and the protocols to serve them with, but is optional
|
||||||
lnHosts := make([]string, 0, len(sblock.pile["bind"]))
|
lnCfgVals := make([]addressesWithProtocols, 0, len(sblock.pile["bind"]))
|
||||||
for _, cfgVal := range sblock.pile["bind"] {
|
for _, cfgVal := range sblock.pile["bind"] {
|
||||||
lnHosts = append(lnHosts, cfgVal.Value.([]string)...)
|
if val, ok := cfgVal.Value.(addressesWithProtocols); ok {
|
||||||
|
lnCfgVals = append(lnCfgVals, val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(lnCfgVals) == 0 {
|
||||||
|
if defaultBindValues, ok := options["default_bind"].([]ConfigValue); ok {
|
||||||
|
for _, defaultBindValue := range defaultBindValues {
|
||||||
|
lnCfgVals = append(lnCfgVals, defaultBindValue.Value.(addressesWithProtocols))
|
||||||
}
|
}
|
||||||
if len(lnHosts) == 0 {
|
|
||||||
if defaultBind, ok := options["default_bind"].([]string); ok {
|
|
||||||
lnHosts = defaultBind
|
|
||||||
} else {
|
} else {
|
||||||
lnHosts = []string{""}
|
lnCfgVals = []addressesWithProtocols{{
|
||||||
|
addresses: []string{""},
|
||||||
|
protocols: nil,
|
||||||
|
}}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// use a map to prevent duplication
|
// use a map to prevent duplication
|
||||||
listeners := make(map[string]struct{})
|
listeners := map[string]map[string]struct{}{}
|
||||||
for _, lnHost := range lnHosts {
|
for _, lnCfgVal := range lnCfgVals {
|
||||||
// normally we would simply append the port,
|
for _, lnHost := range lnCfgVal.addresses {
|
||||||
// but if lnHost is IPv6, we need to ensure it
|
networkAddr, err := caddy.ParseNetworkAddressFromHostPort(lnHost, lnPort)
|
||||||
// is enclosed in [ ]; net.JoinHostPort does
|
|
||||||
// this for us, but lnHost might also have a
|
|
||||||
// network type in front (e.g. "tcp/") leading
|
|
||||||
// to "[tcp/::1]" which causes parsing failures
|
|
||||||
// later; what we need is "tcp/[::1]", so we have
|
|
||||||
// to split the network and host, then re-combine
|
|
||||||
network, host, ok := strings.Cut(lnHost, "/")
|
|
||||||
if !ok {
|
|
||||||
host = network
|
|
||||||
network = ""
|
|
||||||
}
|
|
||||||
host = strings.Trim(host, "[]") // IPv6
|
|
||||||
networkAddr := caddy.JoinNetworkAddress(network, host, lnPort)
|
|
||||||
addr, err := caddy.ParseNetworkAddress(networkAddr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("parsing network address: %v", err)
|
return nil, fmt.Errorf("parsing network address: %v", err)
|
||||||
}
|
}
|
||||||
listeners[addr.String()] = struct{}{}
|
if _, ok := listeners[addr.String()]; !ok {
|
||||||
|
listeners[networkAddr.String()] = map[string]struct{}{}
|
||||||
|
}
|
||||||
|
for _, protocol := range lnCfgVal.protocols {
|
||||||
|
listeners[networkAddr.String()][protocol] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// now turn map into list
|
return listeners, nil
|
||||||
listenersList := make([]string, 0, len(listeners))
|
|
||||||
for lnStr := range listeners {
|
|
||||||
listenersList = append(listenersList, lnStr)
|
|
||||||
}
|
}
|
||||||
sort.Strings(listenersList)
|
|
||||||
|
|
||||||
return listenersList, nil
|
// addressesWithProtocols associates a list of listen addresses
|
||||||
|
// with a list of protocols to serve them with
|
||||||
|
type addressesWithProtocols struct {
|
||||||
|
addresses []string
|
||||||
|
protocols []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Address represents a site address. It contains
|
// Address represents a site address. It contains
|
||||||
|
|||||||
@@ -15,31 +15,30 @@
|
|||||||
package httpcaddyfile
|
package httpcaddyfile
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
|
||||||
"encoding/pem"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"html"
|
"html"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/caddyserver/certmagic"
|
||||||
|
"github.com/mholt/acmez/v2/acme"
|
||||||
|
"go.uber.org/zap/zapcore"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
"github.com/caddyserver/caddy/v2"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||||
"github.com/caddyserver/certmagic"
|
|
||||||
"github.com/mholt/acmez/acme"
|
|
||||||
"go.uber.org/zap/zapcore"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
RegisterDirective("bind", parseBind)
|
RegisterDirective("bind", parseBind)
|
||||||
RegisterDirective("tls", parseTLS)
|
RegisterDirective("tls", parseTLS)
|
||||||
RegisterHandlerDirective("root", parseRoot)
|
RegisterHandlerDirective("fs", parseFilesystem)
|
||||||
|
RegisterDirective("root", parseRoot)
|
||||||
RegisterHandlerDirective("vars", parseVars)
|
RegisterHandlerDirective("vars", parseVars)
|
||||||
RegisterHandlerDirective("redir", parseRedir)
|
RegisterHandlerDirective("redir", parseRedir)
|
||||||
RegisterHandlerDirective("respond", parseRespond)
|
RegisterHandlerDirective("respond", parseRespond)
|
||||||
@@ -50,18 +49,37 @@ func init() {
|
|||||||
RegisterDirective("handle_errors", parseHandleErrors)
|
RegisterDirective("handle_errors", parseHandleErrors)
|
||||||
RegisterHandlerDirective("invoke", parseInvoke)
|
RegisterHandlerDirective("invoke", parseInvoke)
|
||||||
RegisterDirective("log", parseLog)
|
RegisterDirective("log", parseLog)
|
||||||
RegisterHandlerDirective("skip_log", parseSkipLog)
|
RegisterHandlerDirective("skip_log", parseLogSkip)
|
||||||
|
RegisterHandlerDirective("log_skip", parseLogSkip)
|
||||||
|
RegisterHandlerDirective("log_name", parseLogName)
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseBind parses the bind directive. Syntax:
|
// parseBind parses the bind directive. Syntax:
|
||||||
//
|
//
|
||||||
// bind <addresses...>
|
// bind <addresses...> [{
|
||||||
|
// protocols [h1|h2|h2c|h3] [...]
|
||||||
|
// }]
|
||||||
func parseBind(h Helper) ([]ConfigValue, error) {
|
func parseBind(h Helper) ([]ConfigValue, error) {
|
||||||
var lnHosts []string
|
h.Next() // consume directive name
|
||||||
for h.Next() {
|
var addresses, protocols []string
|
||||||
lnHosts = append(lnHosts, h.RemainingArgs()...)
|
addresses = h.RemainingArgs()
|
||||||
|
|
||||||
|
for h.NextBlock(0) {
|
||||||
|
switch h.Val() {
|
||||||
|
case "protocols":
|
||||||
|
protocols = h.RemainingArgs()
|
||||||
|
if len(protocols) == 0 {
|
||||||
|
return nil, h.Errf("protocols requires one or more arguments")
|
||||||
}
|
}
|
||||||
return h.NewBindAddresses(lnHosts), nil
|
default:
|
||||||
|
return nil, h.Errf("unknown subdirective: %s", h.Val())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return []ConfigValue{{Class: "bind", Value: addressesWithProtocols{
|
||||||
|
addresses: addresses,
|
||||||
|
protocols: protocols,
|
||||||
|
}}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseTLS parses the tls directive. Syntax:
|
// parseTLS parses the tls directive. Syntax:
|
||||||
@@ -72,8 +90,7 @@ func parseBind(h Helper) ([]ConfigValue, error) {
|
|||||||
// curves <curves...>
|
// curves <curves...>
|
||||||
// client_auth {
|
// client_auth {
|
||||||
// mode [request|require|verify_if_given|require_and_verify]
|
// mode [request|require|verify_if_given|require_and_verify]
|
||||||
// trusted_ca_cert <base64_der>
|
// trust_pool <module_name> [...]
|
||||||
// trusted_ca_cert_file <filename>
|
|
||||||
// trusted_leaf_cert <base64_der>
|
// trusted_leaf_cert <base64_der>
|
||||||
// trusted_leaf_cert_file <filename>
|
// trusted_leaf_cert_file <filename>
|
||||||
// }
|
// }
|
||||||
@@ -89,12 +106,15 @@ func parseBind(h Helper) ([]ConfigValue, error) {
|
|||||||
// dns_ttl <duration>
|
// dns_ttl <duration>
|
||||||
// dns_challenge_override_domain <domain>
|
// dns_challenge_override_domain <domain>
|
||||||
// on_demand
|
// on_demand
|
||||||
|
// reuse_private_keys
|
||||||
// eab <key_id> <mac_key>
|
// eab <key_id> <mac_key>
|
||||||
// issuer <module_name> [...]
|
// issuer <module_name> [...]
|
||||||
// get_certificate <module_name> [...]
|
// get_certificate <module_name> [...]
|
||||||
// insecure_secrets_log <log_file>
|
// insecure_secrets_log <log_file>
|
||||||
// }
|
// }
|
||||||
func parseTLS(h Helper) ([]ConfigValue, error) {
|
func parseTLS(h Helper) ([]ConfigValue, error) {
|
||||||
|
h.Next() // consume directive name
|
||||||
|
|
||||||
cp := new(caddytls.ConnectionPolicy)
|
cp := new(caddytls.ConnectionPolicy)
|
||||||
var fileLoader caddytls.FileLoader
|
var fileLoader caddytls.FileLoader
|
||||||
var folderLoader caddytls.FolderLoader
|
var folderLoader caddytls.FolderLoader
|
||||||
@@ -105,9 +125,8 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
var issuers []certmagic.Issuer
|
var issuers []certmagic.Issuer
|
||||||
var certManagers []certmagic.Manager
|
var certManagers []certmagic.Manager
|
||||||
var onDemand bool
|
var onDemand bool
|
||||||
|
var reusePrivateKeys bool
|
||||||
|
|
||||||
for h.Next() {
|
|
||||||
// file certificate loader
|
|
||||||
firstLine := h.RemainingArgs()
|
firstLine := h.RemainingArgs()
|
||||||
switch len(firstLine) {
|
switch len(firstLine) {
|
||||||
case 0:
|
case 0:
|
||||||
@@ -117,13 +136,13 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
} else if !strings.Contains(firstLine[0], "@") {
|
} else if !strings.Contains(firstLine[0], "@") {
|
||||||
return nil, h.Err("single argument must either be 'internal' or an email address")
|
return nil, h.Err("single argument must either be 'internal' or an email address")
|
||||||
} else {
|
} else {
|
||||||
if acmeIssuer == nil {
|
acmeIssuer = &caddytls.ACMEIssuer{
|
||||||
acmeIssuer = new(caddytls.ACMEIssuer)
|
Email: firstLine[0],
|
||||||
}
|
}
|
||||||
acmeIssuer.Email = firstLine[0]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
case 2:
|
case 2:
|
||||||
|
// file certificate loader
|
||||||
certFilename := firstLine[0]
|
certFilename := firstLine[0]
|
||||||
keyFilename := firstLine[1]
|
keyFilename := firstLine[1]
|
||||||
|
|
||||||
@@ -173,24 +192,24 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var hasBlock bool
|
var hasBlock bool
|
||||||
for nesting := h.Nesting(); h.NextBlock(nesting); {
|
for h.NextBlock(0) {
|
||||||
hasBlock = true
|
hasBlock = true
|
||||||
|
|
||||||
switch h.Val() {
|
switch h.Val() {
|
||||||
case "protocols":
|
case "protocols":
|
||||||
args := h.RemainingArgs()
|
args := h.RemainingArgs()
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
return nil, h.SyntaxErr("one or two protocols")
|
return nil, h.Errf("protocols requires one or two arguments")
|
||||||
}
|
}
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
if _, ok := caddytls.SupportedProtocols[args[0]]; !ok {
|
if _, ok := caddytls.SupportedProtocols[args[0]]; !ok {
|
||||||
return nil, h.Errf("Wrong protocol name or protocol not supported: '%s'", args[0])
|
return nil, h.Errf("wrong protocol name or protocol not supported: '%s'", args[0])
|
||||||
}
|
}
|
||||||
cp.ProtocolMin = args[0]
|
cp.ProtocolMin = args[0]
|
||||||
}
|
}
|
||||||
if len(args) > 1 {
|
if len(args) > 1 {
|
||||||
if _, ok := caddytls.SupportedProtocols[args[1]]; !ok {
|
if _, ok := caddytls.SupportedProtocols[args[1]]; !ok {
|
||||||
return nil, h.Errf("Wrong protocol name or protocol not supported: '%s'", args[1])
|
return nil, h.Errf("wrong protocol name or protocol not supported: '%s'", args[1])
|
||||||
}
|
}
|
||||||
cp.ProtocolMax = args[1]
|
cp.ProtocolMax = args[1]
|
||||||
}
|
}
|
||||||
@@ -198,7 +217,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
case "ciphers":
|
case "ciphers":
|
||||||
for h.NextArg() {
|
for h.NextArg() {
|
||||||
if !caddytls.CipherSuiteNameSupported(h.Val()) {
|
if !caddytls.CipherSuiteNameSupported(h.Val()) {
|
||||||
return nil, h.Errf("Wrong cipher suite name or cipher suite not supported: '%s'", h.Val())
|
return nil, h.Errf("wrong cipher suite name or cipher suite not supported: '%s'", h.Val())
|
||||||
}
|
}
|
||||||
cp.CipherSuites = append(cp.CipherSuites, h.Val())
|
cp.CipherSuites = append(cp.CipherSuites, h.Val())
|
||||||
}
|
}
|
||||||
@@ -213,55 +232,9 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
|
|
||||||
case "client_auth":
|
case "client_auth":
|
||||||
cp.ClientAuthentication = &caddytls.ClientAuthentication{}
|
cp.ClientAuthentication = &caddytls.ClientAuthentication{}
|
||||||
for nesting := h.Nesting(); h.NextBlock(nesting); {
|
if err := cp.ClientAuthentication.UnmarshalCaddyfile(h.NewFromNextSegment()); err != nil {
|
||||||
subdir := h.Val()
|
|
||||||
switch subdir {
|
|
||||||
case "mode":
|
|
||||||
if !h.Args(&cp.ClientAuthentication.Mode) {
|
|
||||||
return nil, h.ArgErr()
|
|
||||||
}
|
|
||||||
if h.NextArg() {
|
|
||||||
return nil, h.ArgErr()
|
|
||||||
}
|
|
||||||
|
|
||||||
case "trusted_ca_cert",
|
|
||||||
"trusted_leaf_cert":
|
|
||||||
if !h.NextArg() {
|
|
||||||
return nil, h.ArgErr()
|
|
||||||
}
|
|
||||||
if subdir == "trusted_ca_cert" {
|
|
||||||
cp.ClientAuthentication.TrustedCACerts = append(cp.ClientAuthentication.TrustedCACerts, h.Val())
|
|
||||||
} else {
|
|
||||||
cp.ClientAuthentication.TrustedLeafCerts = append(cp.ClientAuthentication.TrustedLeafCerts, h.Val())
|
|
||||||
}
|
|
||||||
|
|
||||||
case "trusted_ca_cert_file",
|
|
||||||
"trusted_leaf_cert_file":
|
|
||||||
if !h.NextArg() {
|
|
||||||
return nil, h.ArgErr()
|
|
||||||
}
|
|
||||||
filename := h.Val()
|
|
||||||
certDataPEM, err := os.ReadFile(filename)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
block, _ := pem.Decode(certDataPEM)
|
|
||||||
if block == nil || block.Type != "CERTIFICATE" {
|
|
||||||
return nil, h.Errf("no CERTIFICATE pem block found in %s", h.Val())
|
|
||||||
}
|
|
||||||
if subdir == "trusted_ca_cert_file" {
|
|
||||||
cp.ClientAuthentication.TrustedCACerts = append(cp.ClientAuthentication.TrustedCACerts,
|
|
||||||
base64.StdEncoding.EncodeToString(block.Bytes))
|
|
||||||
} else {
|
|
||||||
cp.ClientAuthentication.TrustedLeafCerts = append(cp.ClientAuthentication.TrustedLeafCerts,
|
|
||||||
base64.StdEncoding.EncodeToString(block.Bytes))
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
return nil, h.Errf("unknown subdirective for client_auth: %s", subdir)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
case "alpn":
|
case "alpn":
|
||||||
args := h.RemainingArgs()
|
args := h.RemainingArgs()
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
@@ -472,6 +445,12 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
}
|
}
|
||||||
onDemand = true
|
onDemand = true
|
||||||
|
|
||||||
|
case "reuse_private_keys":
|
||||||
|
if h.NextArg() {
|
||||||
|
return nil, h.ArgErr()
|
||||||
|
}
|
||||||
|
reusePrivateKeys = true
|
||||||
|
|
||||||
case "insecure_secrets_log":
|
case "insecure_secrets_log":
|
||||||
if !h.NextArg() {
|
if !h.NextArg() {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
@@ -487,7 +466,6 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
if len(firstLine) == 0 && !hasBlock {
|
if len(firstLine) == 0 && !hasBlock {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// begin building the final config values
|
// begin building the final config values
|
||||||
configVals := []ConfigValue{}
|
configVals := []ConfigValue{}
|
||||||
@@ -529,19 +507,24 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
|
|
||||||
case acmeIssuer != nil:
|
case acmeIssuer != nil:
|
||||||
// implicit ACME issuers (from various subdirectives) - use defaults; there might be more than one
|
// implicit ACME issuers (from various subdirectives) - use defaults; there might be more than one
|
||||||
defaultIssuers := caddytls.DefaultIssuers()
|
defaultIssuers := caddytls.DefaultIssuers(acmeIssuer.Email)
|
||||||
|
|
||||||
// if a CA endpoint was set, override multiple implicit issuers since it's a specific one
|
// if an ACME CA endpoint was set, the user expects to use that specific one,
|
||||||
|
// not any others that may be defaults, so replace all defaults with that ACME CA
|
||||||
if acmeIssuer.CA != "" {
|
if acmeIssuer.CA != "" {
|
||||||
defaultIssuers = []certmagic.Issuer{acmeIssuer}
|
defaultIssuers = []certmagic.Issuer{acmeIssuer}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, issuer := range defaultIssuers {
|
for _, issuer := range defaultIssuers {
|
||||||
switch iss := issuer.(type) {
|
// apply settings from the implicitly-configured ACMEIssuer to any
|
||||||
case *caddytls.ACMEIssuer:
|
// default ACMEIssuers, but preserve each default issuer's CA endpoint,
|
||||||
issuer = acmeIssuer
|
// because, for example, if you configure the DNS challenge, it should
|
||||||
case *caddytls.ZeroSSLIssuer:
|
// apply to any of the default ACMEIssuers, but you don't want to trample
|
||||||
iss.ACMEIssuer = acmeIssuer
|
// out their unique CA endpoints
|
||||||
|
if iss, ok := issuer.(*caddytls.ACMEIssuer); ok && iss != nil {
|
||||||
|
acmeCopy := *acmeIssuer
|
||||||
|
acmeCopy.CA = iss.CA
|
||||||
|
issuer = &acmeCopy
|
||||||
}
|
}
|
||||||
configVals = append(configVals, ConfigValue{
|
configVals = append(configVals, ConfigValue{
|
||||||
Class: "tls.cert_issuer",
|
Class: "tls.cert_issuer",
|
||||||
@@ -578,6 +561,14 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reuse private keys TLS
|
||||||
|
if reusePrivateKeys {
|
||||||
|
configVals = append(configVals, ConfigValue{
|
||||||
|
Class: "tls.reuse_private_keys",
|
||||||
|
Value: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// custom certificate selection
|
// custom certificate selection
|
||||||
if len(certSelector.AnyTag) > 0 {
|
if len(certSelector.AnyTag) > 0 {
|
||||||
cp.CertSelection = &certSelector
|
cp.CertSelection = &certSelector
|
||||||
@@ -599,18 +590,53 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
|||||||
// parseRoot parses the root directive. Syntax:
|
// parseRoot parses the root directive. Syntax:
|
||||||
//
|
//
|
||||||
// root [<matcher>] <path>
|
// root [<matcher>] <path>
|
||||||
func parseRoot(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
func parseRoot(h Helper) ([]ConfigValue, error) {
|
||||||
var root string
|
h.Next() // consume directive name
|
||||||
for h.Next() {
|
|
||||||
|
// count the tokens to determine what to do
|
||||||
|
argsCount := h.CountRemainingArgs()
|
||||||
|
if argsCount == 0 {
|
||||||
|
return nil, h.Errf("too few arguments; must have at least a root path")
|
||||||
|
}
|
||||||
|
if argsCount > 2 {
|
||||||
|
return nil, h.Errf("too many arguments; should only be a matcher and a path")
|
||||||
|
}
|
||||||
|
|
||||||
|
// with only one arg, assume it's a root path with no matcher token
|
||||||
|
if argsCount == 1 {
|
||||||
|
if !h.NextArg() {
|
||||||
|
return nil, h.ArgErr()
|
||||||
|
}
|
||||||
|
return h.NewRoute(nil, caddyhttp.VarsMiddleware{"root": h.Val()}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse the matcher token into a matcher set
|
||||||
|
userMatcherSet, err := h.ExtractMatcherSet()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
h.Next() // consume directive name again, matcher parsing does a reset
|
||||||
|
|
||||||
|
// advance to the root path
|
||||||
|
if !h.NextArg() {
|
||||||
|
return nil, h.ArgErr()
|
||||||
|
}
|
||||||
|
// make the route with the matcher
|
||||||
|
return h.NewRoute(userMatcherSet, caddyhttp.VarsMiddleware{"root": h.Val()}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseFilesystem parses the fs directive. Syntax:
|
||||||
|
//
|
||||||
|
// fs <filesystem>
|
||||||
|
func parseFilesystem(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
|
h.Next() // consume directive name
|
||||||
if !h.NextArg() {
|
if !h.NextArg() {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
}
|
}
|
||||||
root = h.Val()
|
|
||||||
if h.NextArg() {
|
if h.NextArg() {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
}
|
}
|
||||||
}
|
return caddyhttp.VarsMiddleware{"fs": h.Val()}, nil
|
||||||
return caddyhttp.VarsMiddleware{"root": root}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseVars parses the vars directive. See its UnmarshalCaddyfile method for syntax.
|
// parseVars parses the vars directive. See its UnmarshalCaddyfile method for syntax.
|
||||||
@@ -630,10 +656,7 @@ func parseVars(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
// respond with HTTP 200 and no Location header; redirect is performed
|
// respond with HTTP 200 and no Location header; redirect is performed
|
||||||
// with JS and a meta tag).
|
// with JS and a meta tag).
|
||||||
func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
if !h.Next() {
|
h.Next() // consume directive name
|
||||||
return nil, h.ArgErr()
|
|
||||||
}
|
|
||||||
|
|
||||||
if !h.NextArg() {
|
if !h.NextArg() {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
}
|
}
|
||||||
@@ -649,8 +672,10 @@ func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
switch code {
|
switch code {
|
||||||
case "permanent":
|
case "permanent":
|
||||||
code = "301"
|
code = "301"
|
||||||
|
|
||||||
case "temporary", "":
|
case "temporary", "":
|
||||||
code = "302"
|
code = "302"
|
||||||
|
|
||||||
case "html":
|
case "html":
|
||||||
// Script tag comes first since that will better imitate a redirect in the browser's
|
// Script tag comes first since that will better imitate a redirect in the browser's
|
||||||
// history, but the meta tag is a fallback for most non-JS clients.
|
// history, but the meta tag is a fallback for most non-JS clients.
|
||||||
@@ -666,7 +691,9 @@ func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
`
|
`
|
||||||
safeTo := html.EscapeString(to)
|
safeTo := html.EscapeString(to)
|
||||||
body = fmt.Sprintf(metaRedir, safeTo, safeTo, safeTo, safeTo)
|
body = fmt.Sprintf(metaRedir, safeTo, safeTo, safeTo, safeTo)
|
||||||
|
hdr = http.Header{"Content-Type": []string{"text/html; charset=utf-8"}}
|
||||||
code = "200" // don't redirect non-browser clients
|
code = "200" // don't redirect non-browser clients
|
||||||
|
|
||||||
default:
|
default:
|
||||||
// Allow placeholders for the code
|
// Allow placeholders for the code
|
||||||
if strings.HasPrefix(code, "{") {
|
if strings.HasPrefix(code, "{") {
|
||||||
@@ -705,10 +732,7 @@ func parseRedir(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
func parseRespond(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
func parseRespond(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
sr := new(caddyhttp.StaticResponse)
|
sr := new(caddyhttp.StaticResponse)
|
||||||
err := sr.UnmarshalCaddyfile(h.Dispenser)
|
err := sr.UnmarshalCaddyfile(h.Dispenser)
|
||||||
if err != nil {
|
return sr, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return sr, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseAbort parses the abort directive.
|
// parseAbort parses the abort directive.
|
||||||
@@ -724,10 +748,7 @@ func parseAbort(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
func parseError(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
func parseError(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
se := new(caddyhttp.StaticError)
|
se := new(caddyhttp.StaticError)
|
||||||
err := se.UnmarshalCaddyfile(h.Dispenser)
|
err := se.UnmarshalCaddyfile(h.Dispenser)
|
||||||
if err != nil {
|
return se, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return se, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseRoute parses the route directive.
|
// parseRoute parses the route directive.
|
||||||
@@ -753,10 +774,67 @@ func parseHandle(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseHandleErrors(h Helper) ([]ConfigValue, error) {
|
func parseHandleErrors(h Helper) ([]ConfigValue, error) {
|
||||||
subroute, err := ParseSegmentAsSubroute(h)
|
h.Next() // consume directive name
|
||||||
|
|
||||||
|
expression := ""
|
||||||
|
args := h.RemainingArgs()
|
||||||
|
if len(args) > 0 {
|
||||||
|
codes := []string{}
|
||||||
|
for _, val := range args {
|
||||||
|
if len(val) != 3 {
|
||||||
|
return nil, h.Errf("bad status value '%s'", val)
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(val, "xx") {
|
||||||
|
val = val[:1]
|
||||||
|
_, err := strconv.Atoi(val)
|
||||||
|
if err != nil {
|
||||||
|
return nil, h.Errf("bad status value '%s': %v", val, err)
|
||||||
|
}
|
||||||
|
if expression != "" {
|
||||||
|
expression += " || "
|
||||||
|
}
|
||||||
|
expression += fmt.Sprintf("{http.error.status_code} >= %s00 && {http.error.status_code} <= %s99", val, val)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, err := strconv.Atoi(val)
|
||||||
|
if err != nil {
|
||||||
|
return nil, h.Errf("bad status value '%s': %v", val, err)
|
||||||
|
}
|
||||||
|
codes = append(codes, val)
|
||||||
|
}
|
||||||
|
if len(codes) > 0 {
|
||||||
|
if expression != "" {
|
||||||
|
expression += " || "
|
||||||
|
}
|
||||||
|
expression += "{http.error.status_code} in [" + strings.Join(codes, ", ") + "]"
|
||||||
|
}
|
||||||
|
// Reset cursor position to get ready for ParseSegmentAsSubroute
|
||||||
|
h.Reset()
|
||||||
|
h.Next()
|
||||||
|
h.RemainingArgs()
|
||||||
|
h.Prev()
|
||||||
|
} else {
|
||||||
|
// If no arguments present reset the cursor position to get ready for ParseSegmentAsSubroute
|
||||||
|
h.Prev()
|
||||||
|
}
|
||||||
|
|
||||||
|
handler, err := ParseSegmentAsSubroute(h)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
subroute, ok := handler.(*caddyhttp.Subroute)
|
||||||
|
if !ok {
|
||||||
|
return nil, h.Errf("segment was not parsed as a subroute")
|
||||||
|
}
|
||||||
|
|
||||||
|
if expression != "" {
|
||||||
|
statusMatcher := caddy.ModuleMap{
|
||||||
|
"expression": h.JSON(caddyhttp.MatchExpression{Expr: expression}),
|
||||||
|
}
|
||||||
|
for i := range subroute.Routes {
|
||||||
|
subroute.Routes[i].MatcherSetsRaw = []caddy.ModuleMap{statusMatcher}
|
||||||
|
}
|
||||||
|
}
|
||||||
return []ConfigValue{
|
return []ConfigValue{
|
||||||
{
|
{
|
||||||
Class: "error_route",
|
Class: "error_route",
|
||||||
@@ -791,6 +869,7 @@ func parseInvoke(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
|||||||
// log <logger_name> {
|
// log <logger_name> {
|
||||||
// hostnames <hostnames...>
|
// hostnames <hostnames...>
|
||||||
// output <writer_module> ...
|
// output <writer_module> ...
|
||||||
|
// core <core_module> ...
|
||||||
// format <encoder_module> ...
|
// format <encoder_module> ...
|
||||||
// level <level>
|
// level <level>
|
||||||
// }
|
// }
|
||||||
@@ -803,12 +882,14 @@ func parseLog(h Helper) ([]ConfigValue, error) {
|
|||||||
// level. The parseAsGlobalOption parameter is used to distinguish any differing logic
|
// level. The parseAsGlobalOption parameter is used to distinguish any differing logic
|
||||||
// between the two.
|
// between the two.
|
||||||
func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue, error) {
|
func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue, error) {
|
||||||
|
h.Next() // consume option name
|
||||||
|
|
||||||
// When the globalLogNames parameter is passed in, we make
|
// When the globalLogNames parameter is passed in, we make
|
||||||
// modifications to the parsing behavior.
|
// modifications to the parsing behavior.
|
||||||
parseAsGlobalOption := globalLogNames != nil
|
parseAsGlobalOption := globalLogNames != nil
|
||||||
|
|
||||||
var configValues []ConfigValue
|
var configValues []ConfigValue
|
||||||
for h.Next() {
|
|
||||||
// Logic below expects that a name is always present when a
|
// Logic below expects that a name is always present when a
|
||||||
// global option is being parsed; or an optional override
|
// global option is being parsed; or an optional override
|
||||||
// is supported for access logs.
|
// is supported for access logs.
|
||||||
@@ -855,7 +936,7 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
|||||||
// this is useful for setting up loggers per subdomain in a site block
|
// this is useful for setting up loggers per subdomain in a site block
|
||||||
// with a wildcard domain
|
// with a wildcard domain
|
||||||
customHostnames := []string{}
|
customHostnames := []string{}
|
||||||
|
noHostname := false
|
||||||
for h.NextBlock(0) {
|
for h.NextBlock(0) {
|
||||||
switch h.Val() {
|
switch h.Val() {
|
||||||
case "hostnames":
|
case "hostnames":
|
||||||
@@ -900,6 +981,22 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
|||||||
}
|
}
|
||||||
cl.WriterRaw = caddyconfig.JSONModuleObject(wo, "output", moduleName, h.warnings)
|
cl.WriterRaw = caddyconfig.JSONModuleObject(wo, "output", moduleName, h.warnings)
|
||||||
|
|
||||||
|
case "core":
|
||||||
|
if !h.NextArg() {
|
||||||
|
return nil, h.ArgErr()
|
||||||
|
}
|
||||||
|
moduleName := h.Val()
|
||||||
|
moduleID := "caddy.logging.cores." + moduleName
|
||||||
|
unm, err := caddyfile.UnmarshalModule(h.Dispenser, moduleID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
core, ok := unm.(zapcore.Core)
|
||||||
|
if !ok {
|
||||||
|
return nil, h.Errf("module %s (%T) is not a zapcore.Core", moduleID, unm)
|
||||||
|
}
|
||||||
|
cl.CoreRaw = caddyconfig.JSONModuleObject(core, "module", moduleName, h.warnings)
|
||||||
|
|
||||||
case "format":
|
case "format":
|
||||||
if !h.NextArg() {
|
if !h.NextArg() {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
@@ -941,6 +1038,12 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
|||||||
cl.Exclude = append(cl.Exclude, h.Val())
|
cl.Exclude = append(cl.Exclude, h.Val())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case "no_hostname":
|
||||||
|
if h.NextArg() {
|
||||||
|
return nil, h.ArgErr()
|
||||||
|
}
|
||||||
|
noHostname = true
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nil, h.Errf("unrecognized subdirective: %s", h.Val())
|
return nil, h.Errf("unrecognized subdirective: %s", h.Val())
|
||||||
}
|
}
|
||||||
@@ -948,7 +1051,7 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
|||||||
|
|
||||||
var val namedCustomLog
|
var val namedCustomLog
|
||||||
val.hostnames = customHostnames
|
val.hostnames = customHostnames
|
||||||
|
val.noHostname = noHostname
|
||||||
isEmptyConfig := reflect.DeepEqual(cl, new(caddy.CustomLog))
|
isEmptyConfig := reflect.DeepEqual(cl, new(caddy.CustomLog))
|
||||||
|
|
||||||
// Skip handling of empty logging configs
|
// Skip handling of empty logging configs
|
||||||
@@ -980,18 +1083,32 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
|||||||
Class: "custom_log",
|
Class: "custom_log",
|
||||||
Value: val,
|
Value: val,
|
||||||
})
|
})
|
||||||
}
|
|
||||||
return configValues, nil
|
return configValues, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseSkipLog parses the skip_log directive. Syntax:
|
// parseLogSkip parses the log_skip directive. Syntax:
|
||||||
//
|
//
|
||||||
// skip_log [<matcher>]
|
// log_skip [<matcher>]
|
||||||
func parseSkipLog(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
func parseLogSkip(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
for h.Next() {
|
h.Next() // consume directive name
|
||||||
|
|
||||||
|
// "skip_log" is deprecated, replaced by "log_skip"
|
||||||
|
if h.Val() == "skip_log" {
|
||||||
|
caddy.Log().Named("config.adapter.caddyfile").Warn("the 'skip_log' directive is deprecated, please use 'log_skip' instead!")
|
||||||
|
}
|
||||||
|
|
||||||
if h.NextArg() {
|
if h.NextArg() {
|
||||||
return nil, h.ArgErr()
|
return nil, h.ArgErr()
|
||||||
}
|
}
|
||||||
|
return caddyhttp.VarsMiddleware{"log_skip": true}, nil
|
||||||
}
|
}
|
||||||
return caddyhttp.VarsMiddleware{"skip_log": true}, nil
|
|
||||||
|
// parseLogName parses the log_name directive. Syntax:
|
||||||
|
//
|
||||||
|
// log_name <names...>
|
||||||
|
func parseLogName(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||||
|
h.Next() // consume directive name
|
||||||
|
return caddyhttp.VarsMiddleware{
|
||||||
|
caddyhttp.AccessLoggerNameVarKey: h.RemainingArgs(),
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,11 +25,12 @@ func TestLogDirectiveSyntax(t *testing.T) {
|
|||||||
{
|
{
|
||||||
input: `:8080 {
|
input: `:8080 {
|
||||||
log {
|
log {
|
||||||
|
core mock
|
||||||
output file foo.log
|
output file foo.log
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.log0"]},"log0":{"writer":{"filename":"foo.log","output":"file"},"include":["http.log.access.log0"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"log0"}}}}}}`,
|
output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.log0"]},"log0":{"writer":{"filename":"foo.log","output":"file"},"core":{"module":"mock"},"include":["http.log.access.log0"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"log0"}}}}}}`,
|
||||||
expectError: false,
|
expectError: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -53,11 +54,12 @@ func TestLogDirectiveSyntax(t *testing.T) {
|
|||||||
{
|
{
|
||||||
input: `:8080 {
|
input: `:8080 {
|
||||||
log name-override {
|
log name-override {
|
||||||
|
core mock
|
||||||
output file foo.log
|
output file foo.log
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.name-override"]},"name-override":{"writer":{"filename":"foo.log","output":"file"},"include":["http.log.access.name-override"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"name-override"}}}}}}`,
|
output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.name-override"]},"name-override":{"writer":{"filename":"foo.log","output":"file"},"core":{"module":"mock"},"include":["http.log.access.name-override"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"name-override"}}}}}}`,
|
||||||
expectError: false,
|
expectError: false,
|
||||||
},
|
},
|
||||||
} {
|
} {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ package httpcaddyfile
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net"
|
"net"
|
||||||
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -27,22 +28,33 @@ import (
|
|||||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// directiveOrder specifies the order
|
// defaultDirectiveOrder specifies the default order
|
||||||
// to apply directives in HTTP routes.
|
// to apply directives in HTTP routes. This must only
|
||||||
|
// consist of directives that are included in Caddy's
|
||||||
|
// standard distribution.
|
||||||
//
|
//
|
||||||
// The root directive goes first in case rewrites or
|
// e.g. The 'root' directive goes near the start in
|
||||||
// redirects depend on existence of files, i.e. the
|
// case rewrites or redirects depend on existence of
|
||||||
// file matcher, which must know the root first.
|
// files, i.e. the file matcher, which must know the
|
||||||
|
// root first.
|
||||||
//
|
//
|
||||||
// The header directive goes second so that headers
|
// e.g. The 'header' directive goes before 'redir' so
|
||||||
// can be manipulated before doing redirects.
|
// that headers can be manipulated before doing redirects.
|
||||||
var directiveOrder = []string{
|
//
|
||||||
|
// e.g. The 'respond' directive is near the end because it
|
||||||
|
// writes a response and terminates the middleware chain.
|
||||||
|
var defaultDirectiveOrder = []string{
|
||||||
"tracing",
|
"tracing",
|
||||||
|
|
||||||
|
// set variables that may be used by other directives
|
||||||
"map",
|
"map",
|
||||||
"vars",
|
"vars",
|
||||||
|
"fs",
|
||||||
"root",
|
"root",
|
||||||
"skip_log",
|
"log_append",
|
||||||
|
"skip_log", // TODO: deprecated, renamed to log_skip
|
||||||
|
"log_skip",
|
||||||
|
"log_name",
|
||||||
|
|
||||||
"header",
|
"header",
|
||||||
"copy_response_headers", // only in reverse_proxy's handle_response
|
"copy_response_headers", // only in reverse_proxy's handle_response
|
||||||
@@ -57,11 +69,13 @@ var directiveOrder = []string{
|
|||||||
"try_files",
|
"try_files",
|
||||||
|
|
||||||
// middleware handlers; some wrap responses
|
// middleware handlers; some wrap responses
|
||||||
"basicauth",
|
"basicauth", // TODO: deprecated, renamed to basic_auth
|
||||||
|
"basic_auth",
|
||||||
"forward_auth",
|
"forward_auth",
|
||||||
"request_header",
|
"request_header",
|
||||||
"encode",
|
"encode",
|
||||||
"push",
|
"push",
|
||||||
|
"intercept",
|
||||||
"templates",
|
"templates",
|
||||||
|
|
||||||
// special routing & dispatching directives
|
// special routing & dispatching directives
|
||||||
@@ -82,16 +96,10 @@ var directiveOrder = []string{
|
|||||||
"acme_server",
|
"acme_server",
|
||||||
}
|
}
|
||||||
|
|
||||||
// directiveIsOrdered returns true if dir is
|
// directiveOrder specifies the order to apply directives
|
||||||
// a known, ordered (sorted) directive.
|
// in HTTP routes, after being modified by either the
|
||||||
func directiveIsOrdered(dir string) bool {
|
// plugins or by the user via the "order" global option.
|
||||||
for _, d := range directiveOrder {
|
var directiveOrder = defaultDirectiveOrder
|
||||||
if d == dir {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// RegisterDirective registers a unique directive dir with an
|
// RegisterDirective registers a unique directive dir with an
|
||||||
// associated unmarshaling (setup) function. When directive dir
|
// associated unmarshaling (setup) function. When directive dir
|
||||||
@@ -128,6 +136,53 @@ func RegisterHandlerDirective(dir string, setupFunc UnmarshalHandlerFunc) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RegisterDirectiveOrder registers the default order for a
|
||||||
|
// directive from a plugin.
|
||||||
|
//
|
||||||
|
// This is useful when a plugin has a well-understood place
|
||||||
|
// it should run in the middleware pipeline, and it allows
|
||||||
|
// users to avoid having to define the order themselves.
|
||||||
|
//
|
||||||
|
// The directive dir may be placed in the position relative
|
||||||
|
// to ('before' or 'after') a directive included in Caddy's
|
||||||
|
// standard distribution. It cannot be relative to another
|
||||||
|
// plugin's directive.
|
||||||
|
//
|
||||||
|
// EXPERIMENTAL: This API may change or be removed.
|
||||||
|
func RegisterDirectiveOrder(dir string, position Positional, standardDir string) {
|
||||||
|
// check if directive was already ordered
|
||||||
|
if slices.Contains(directiveOrder, dir) {
|
||||||
|
panic("directive '" + dir + "' already ordered")
|
||||||
|
}
|
||||||
|
|
||||||
|
if position != Before && position != After {
|
||||||
|
panic("the 2nd argument must be either 'before' or 'after', got '" + position + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if directive exists in standard distribution, since
|
||||||
|
// we can't allow plugins to depend on one another; we can't
|
||||||
|
// guarantee the order that plugins are loaded in.
|
||||||
|
foundStandardDir := slices.Contains(defaultDirectiveOrder, standardDir)
|
||||||
|
if !foundStandardDir {
|
||||||
|
panic("the 3rd argument '" + standardDir + "' must be a directive that exists in the standard distribution of Caddy")
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert directive into proper position
|
||||||
|
newOrder := directiveOrder
|
||||||
|
for i, d := range newOrder {
|
||||||
|
if d != standardDir {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if position == Before {
|
||||||
|
newOrder = append(newOrder[:i], append([]string{dir}, newOrder[i:]...)...)
|
||||||
|
} else if position == After {
|
||||||
|
newOrder = append(newOrder[:i+1], append([]string{dir}, newOrder[i+1:]...)...)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
directiveOrder = newOrder
|
||||||
|
}
|
||||||
|
|
||||||
// RegisterGlobalOption registers a unique global option opt with
|
// RegisterGlobalOption registers a unique global option opt with
|
||||||
// an associated unmarshaling (setup) function. When the global
|
// an associated unmarshaling (setup) function. When the global
|
||||||
// option opt is encountered in a Caddyfile, setupFunc will be
|
// option opt is encountered in a Caddyfile, setupFunc will be
|
||||||
@@ -217,7 +272,8 @@ func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
|
|||||||
|
|
||||||
// NewRoute returns config values relevant to creating a new HTTP route.
|
// NewRoute returns config values relevant to creating a new HTTP route.
|
||||||
func (h Helper) NewRoute(matcherSet caddy.ModuleMap,
|
func (h Helper) NewRoute(matcherSet caddy.ModuleMap,
|
||||||
handler caddyhttp.MiddlewareHandler) []ConfigValue {
|
handler caddyhttp.MiddlewareHandler,
|
||||||
|
) []ConfigValue {
|
||||||
mod, err := caddy.GetModule(caddy.GetModuleID(handler))
|
mod, err := caddy.GetModule(caddy.GetModuleID(handler))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
*h.warnings = append(*h.warnings, caddyconfig.Warning{
|
*h.warnings = append(*h.warnings, caddyconfig.Warning{
|
||||||
@@ -269,12 +325,6 @@ func (h Helper) GroupRoutes(vals []ConfigValue) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewBindAddresses returns config values relevant to adding
|
|
||||||
// listener bind addresses to the config.
|
|
||||||
func (h Helper) NewBindAddresses(addrs []string) []ConfigValue {
|
|
||||||
return []ConfigValue{{Class: "bind", Value: addrs}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithDispenser returns a new instance based on d. All others Helper
|
// WithDispenser returns a new instance based on d. All others Helper
|
||||||
// fields are copied, so typically maps are shared with this new instance.
|
// fields are copied, so typically maps are shared with this new instance.
|
||||||
func (h Helper) WithDispenser(d *caddyfile.Dispenser) Helper {
|
func (h Helper) WithDispenser(d *caddyfile.Dispenser) Helper {
|
||||||
@@ -468,7 +518,7 @@ func sortRoutes(routes []ConfigValue) {
|
|||||||
type serverBlock struct {
|
type serverBlock struct {
|
||||||
block caddyfile.ServerBlock
|
block caddyfile.ServerBlock
|
||||||
pile map[string][]ConfigValue // config values obtained from directives
|
pile map[string][]ConfigValue // config values obtained from directives
|
||||||
keys []Address
|
parsedKeys []Address
|
||||||
}
|
}
|
||||||
|
|
||||||
// hostsFromKeys returns a list of all the non-empty hostnames found in
|
// hostsFromKeys returns a list of all the non-empty hostnames found in
|
||||||
@@ -485,7 +535,7 @@ type serverBlock struct {
|
|||||||
func (sb serverBlock) hostsFromKeys(loggerMode bool) []string {
|
func (sb serverBlock) hostsFromKeys(loggerMode bool) []string {
|
||||||
// ensure each entry in our list is unique
|
// ensure each entry in our list is unique
|
||||||
hostMap := make(map[string]struct{})
|
hostMap := make(map[string]struct{})
|
||||||
for _, addr := range sb.keys {
|
for _, addr := range sb.parsedKeys {
|
||||||
if addr.Host == "" {
|
if addr.Host == "" {
|
||||||
if !loggerMode {
|
if !loggerMode {
|
||||||
// server block contains a key like ":443", i.e. the host portion
|
// server block contains a key like ":443", i.e. the host portion
|
||||||
@@ -517,7 +567,7 @@ func (sb serverBlock) hostsFromKeys(loggerMode bool) []string {
|
|||||||
func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string {
|
func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string {
|
||||||
// ensure each entry in our list is unique
|
// ensure each entry in our list is unique
|
||||||
hostMap := make(map[string]struct{})
|
hostMap := make(map[string]struct{})
|
||||||
for _, addr := range sb.keys {
|
for _, addr := range sb.parsedKeys {
|
||||||
if addr.Host == "" {
|
if addr.Host == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -538,25 +588,29 @@ func (sb serverBlock) hostsFromKeysNotHTTP(httpPort string) []string {
|
|||||||
// hasHostCatchAllKey returns true if sb has a key that
|
// hasHostCatchAllKey returns true if sb has a key that
|
||||||
// omits a host portion, i.e. it "catches all" hosts.
|
// omits a host portion, i.e. it "catches all" hosts.
|
||||||
func (sb serverBlock) hasHostCatchAllKey() bool {
|
func (sb serverBlock) hasHostCatchAllKey() bool {
|
||||||
for _, addr := range sb.keys {
|
return slices.ContainsFunc(sb.parsedKeys, func(addr Address) bool {
|
||||||
if addr.Host == "" {
|
return addr.Host == ""
|
||||||
return true
|
})
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// isAllHTTP returns true if all sb keys explicitly specify
|
// isAllHTTP returns true if all sb keys explicitly specify
|
||||||
// the http:// scheme
|
// the http:// scheme
|
||||||
func (sb serverBlock) isAllHTTP() bool {
|
func (sb serverBlock) isAllHTTP() bool {
|
||||||
for _, addr := range sb.keys {
|
return !slices.ContainsFunc(sb.parsedKeys, func(addr Address) bool {
|
||||||
if addr.Scheme != "http" {
|
return addr.Scheme != "http"
|
||||||
return false
|
})
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Positional are the supported modes for ordering directives.
|
||||||
|
type Positional string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Before Positional = "before"
|
||||||
|
After Positional = "after"
|
||||||
|
First Positional = "first"
|
||||||
|
Last Positional = "last"
|
||||||
|
)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
// UnmarshalFunc is a function which can unmarshal Caddyfile
|
// UnmarshalFunc is a function which can unmarshal Caddyfile
|
||||||
// tokens into zero or more config values using a Helper type.
|
// tokens into zero or more config values using a Helper type.
|
||||||
|
|||||||
@@ -31,20 +31,23 @@ func TestHostsFromKeys(t *testing.T) {
|
|||||||
[]Address{
|
[]Address{
|
||||||
{Original: ":2015", Port: "2015"},
|
{Original: ":2015", Port: "2015"},
|
||||||
},
|
},
|
||||||
[]string{}, []string{},
|
[]string{},
|
||||||
|
[]string{},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
[]Address{
|
[]Address{
|
||||||
{Original: ":443", Port: "443"},
|
{Original: ":443", Port: "443"},
|
||||||
},
|
},
|
||||||
[]string{}, []string{},
|
[]string{},
|
||||||
|
[]string{},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
[]Address{
|
[]Address{
|
||||||
{Original: "foo", Host: "foo"},
|
{Original: "foo", Host: "foo"},
|
||||||
{Original: ":2015", Port: "2015"},
|
{Original: ":2015", Port: "2015"},
|
||||||
},
|
},
|
||||||
[]string{}, []string{"foo"},
|
[]string{},
|
||||||
|
[]string{"foo"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
[]Address{
|
[]Address{
|
||||||
@@ -75,7 +78,7 @@ func TestHostsFromKeys(t *testing.T) {
|
|||||||
[]string{"example.com:2015"},
|
[]string{"example.com:2015"},
|
||||||
},
|
},
|
||||||
} {
|
} {
|
||||||
sb := serverBlock{keys: tc.keys}
|
sb := serverBlock{parsedKeys: tc.keys}
|
||||||
|
|
||||||
// test in normal mode
|
// test in normal mode
|
||||||
actual := sb.hostsFromKeys(false)
|
actual := sb.hostsFromKeys(false)
|
||||||
|
|||||||
@@ -17,20 +17,21 @@ package httpcaddyfile
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
"github.com/caddyserver/caddy/v2"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddypki"
|
"github.com/caddyserver/caddy/v2/modules/caddypki"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||||
"go.uber.org/zap"
|
|
||||||
"golang.org/x/exp/slices"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
@@ -49,8 +50,7 @@ type App struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ServerType can set up a config from an HTTP Caddyfile.
|
// ServerType can set up a config from an HTTP Caddyfile.
|
||||||
type ServerType struct {
|
type ServerType struct{}
|
||||||
}
|
|
||||||
|
|
||||||
// Setup makes a config from the tokens.
|
// Setup makes a config from the tokens.
|
||||||
func (st ServerType) Setup(
|
func (st ServerType) Setup(
|
||||||
@@ -65,8 +65,11 @@ func (st ServerType) Setup(
|
|||||||
originalServerBlocks := make([]serverBlock, 0, len(inputServerBlocks))
|
originalServerBlocks := make([]serverBlock, 0, len(inputServerBlocks))
|
||||||
for _, sblock := range inputServerBlocks {
|
for _, sblock := range inputServerBlocks {
|
||||||
for j, k := range sblock.Keys {
|
for j, k := range sblock.Keys {
|
||||||
if j == 0 && strings.HasPrefix(k, "@") {
|
if j == 0 && strings.HasPrefix(k.Text, "@") {
|
||||||
return nil, warnings, fmt.Errorf("cannot define a matcher outside of a site block: '%s'", k)
|
return nil, warnings, fmt.Errorf("%s:%d: cannot define a matcher outside of a site block: '%s'", k.File, k.Line, k.Text)
|
||||||
|
}
|
||||||
|
if _, ok := registeredDirectives[k.Text]; ok {
|
||||||
|
return nil, warnings, fmt.Errorf("%s:%d: parsed '%s' as a site address, but it is a known directive; directives must appear in a site block", k.File, k.Line, k.Text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
originalServerBlocks = append(originalServerBlocks, serverBlock{
|
originalServerBlocks = append(originalServerBlocks, serverBlock{
|
||||||
@@ -82,46 +85,18 @@ func (st ServerType) Setup(
|
|||||||
return nil, warnings, err
|
return nil, warnings, err
|
||||||
}
|
}
|
||||||
|
|
||||||
originalServerBlocks, err = st.extractNamedRoutes(originalServerBlocks, options, &warnings)
|
// this will replace both static and user-defined placeholder shorthands
|
||||||
|
// with actual identifiers used by Caddy
|
||||||
|
replacer := NewShorthandReplacer()
|
||||||
|
|
||||||
|
originalServerBlocks, err = st.extractNamedRoutes(originalServerBlocks, options, &warnings, replacer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, warnings, err
|
return nil, warnings, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// replace shorthand placeholders (which are convenient
|
|
||||||
// when writing a Caddyfile) with their actual placeholder
|
|
||||||
// identifiers or variable names
|
|
||||||
replacer := strings.NewReplacer(placeholderShorthands()...)
|
|
||||||
|
|
||||||
// these are placeholders that allow a user-defined final
|
|
||||||
// parameters, but we still want to provide a shorthand
|
|
||||||
// for those, so we use a regexp to replace
|
|
||||||
regexpReplacements := []struct {
|
|
||||||
search *regexp.Regexp
|
|
||||||
replace string
|
|
||||||
}{
|
|
||||||
{regexp.MustCompile(`{header\.([\w-]*)}`), "{http.request.header.$1}"},
|
|
||||||
{regexp.MustCompile(`{cookie\.([\w-]*)}`), "{http.request.cookie.$1}"},
|
|
||||||
{regexp.MustCompile(`{labels\.([\w-]*)}`), "{http.request.host.labels.$1}"},
|
|
||||||
{regexp.MustCompile(`{path\.([\w-]*)}`), "{http.request.uri.path.$1}"},
|
|
||||||
{regexp.MustCompile(`{file\.([\w-]*)}`), "{http.request.uri.path.file.$1}"},
|
|
||||||
{regexp.MustCompile(`{query\.([\w-]*)}`), "{http.request.uri.query.$1}"},
|
|
||||||
{regexp.MustCompile(`{re\.([\w-]*)\.([\w-]*)}`), "{http.regexp.$1.$2}"},
|
|
||||||
{regexp.MustCompile(`{vars\.([\w-]*)}`), "{http.vars.$1}"},
|
|
||||||
{regexp.MustCompile(`{rp\.([\w-\.]*)}`), "{http.reverse_proxy.$1}"},
|
|
||||||
{regexp.MustCompile(`{err\.([\w-\.]*)}`), "{http.error.$1}"},
|
|
||||||
{regexp.MustCompile(`{file_match\.([\w-]*)}`), "{http.matchers.file.$1}"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, sb := range originalServerBlocks {
|
for _, sb := range originalServerBlocks {
|
||||||
for _, segment := range sb.block.Segments {
|
for i := range sb.block.Segments {
|
||||||
for i := 0; i < len(segment); i++ {
|
replacer.ApplyToSegment(&sb.block.Segments[i])
|
||||||
// simple string replacements
|
|
||||||
segment[i].Text = replacer.Replace(segment[i].Text)
|
|
||||||
// complex regexp replacements
|
|
||||||
for _, r := range regexpReplacements {
|
|
||||||
segment[i].Text = r.search.ReplaceAllString(segment[i].Text, r.replace)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(sb.block.Keys) == 0 {
|
if len(sb.block.Keys) == 0 {
|
||||||
@@ -196,7 +171,7 @@ func (st ServerType) Setup(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// map
|
// map
|
||||||
sbmap, err := st.mapAddressToServerBlocks(originalServerBlocks, options)
|
sbmap, err := st.mapAddressToProtocolToServerBlocks(originalServerBlocks, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, warnings, err
|
return nil, warnings, err
|
||||||
}
|
}
|
||||||
@@ -299,6 +274,12 @@ func (st ServerType) Setup(
|
|||||||
if !reflect.DeepEqual(pkiApp, &caddypki.PKI{CAs: make(map[string]*caddypki.CA)}) {
|
if !reflect.DeepEqual(pkiApp, &caddypki.PKI{CAs: make(map[string]*caddypki.CA)}) {
|
||||||
cfg.AppsRaw["pki"] = caddyconfig.JSON(pkiApp, &warnings)
|
cfg.AppsRaw["pki"] = caddyconfig.JSON(pkiApp, &warnings)
|
||||||
}
|
}
|
||||||
|
if filesystems, ok := options["filesystem"].(caddy.Module); ok {
|
||||||
|
cfg.AppsRaw["caddy.filesystems"] = caddyconfig.JSON(
|
||||||
|
filesystems,
|
||||||
|
&warnings)
|
||||||
|
}
|
||||||
|
|
||||||
if storageCvtr, ok := options["storage"].(caddy.StorageConverter); ok {
|
if storageCvtr, ok := options["storage"].(caddy.StorageConverter); ok {
|
||||||
cfg.StorageRaw = caddyconfig.JSONModuleObject(storageCvtr,
|
cfg.StorageRaw = caddyconfig.JSONModuleObject(storageCvtr,
|
||||||
"module",
|
"module",
|
||||||
@@ -308,7 +289,6 @@ func (st ServerType) Setup(
|
|||||||
if adminConfig, ok := options["admin"].(*caddy.AdminConfig); ok && adminConfig != nil {
|
if adminConfig, ok := options["admin"].(*caddy.AdminConfig); ok && adminConfig != nil {
|
||||||
cfg.Admin = adminConfig
|
cfg.Admin = adminConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
if pc, ok := options["persist_config"].(string); ok && pc == "off" {
|
if pc, ok := options["persist_config"].(string); ok && pc == "off" {
|
||||||
if cfg.Admin == nil {
|
if cfg.Admin == nil {
|
||||||
cfg.Admin = new(caddy.AdminConfig)
|
cfg.Admin = new(caddy.AdminConfig)
|
||||||
@@ -422,6 +402,20 @@ func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options
|
|||||||
options[opt] = append(existingOpts, logOpts...)
|
options[opt] = append(existingOpts, logOpts...)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// Also fold multiple "default_bind" options together into an
|
||||||
|
// array so that server blocks can have multiple binds by default.
|
||||||
|
if opt == "default_bind" {
|
||||||
|
existingOpts, ok := options[opt].([]ConfigValue)
|
||||||
|
if !ok {
|
||||||
|
existingOpts = []ConfigValue{}
|
||||||
|
}
|
||||||
|
defaultBindOpts, ok := val.([]ConfigValue)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("unexpected type from 'default_bind' global options: %T", val)
|
||||||
|
}
|
||||||
|
options[opt] = append(existingOpts, defaultBindOpts...)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
options[opt] = val
|
options[opt] = val
|
||||||
}
|
}
|
||||||
@@ -452,6 +446,7 @@ func (ServerType) extractNamedRoutes(
|
|||||||
serverBlocks []serverBlock,
|
serverBlocks []serverBlock,
|
||||||
options map[string]any,
|
options map[string]any,
|
||||||
warnings *[]caddyconfig.Warning,
|
warnings *[]caddyconfig.Warning,
|
||||||
|
replacer ShorthandReplacer,
|
||||||
) ([]serverBlock, error) {
|
) ([]serverBlock, error) {
|
||||||
namedRoutes := map[string]*caddyhttp.Route{}
|
namedRoutes := map[string]*caddyhttp.Route{}
|
||||||
|
|
||||||
@@ -477,11 +472,14 @@ func (ServerType) extractNamedRoutes(
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
wholeSegment := caddyfile.Segment{}
|
||||||
|
for i := range sb.block.Segments {
|
||||||
|
// replace user-defined placeholder shorthands in extracted named routes
|
||||||
|
replacer.ApplyToSegment(&sb.block.Segments[i])
|
||||||
|
|
||||||
// zip up all the segments since ParseSegmentAsSubroute
|
// zip up all the segments since ParseSegmentAsSubroute
|
||||||
// was designed to take a directive+
|
// was designed to take a directive+
|
||||||
wholeSegment := caddyfile.Segment{}
|
wholeSegment = append(wholeSegment, sb.block.Segments[i]...)
|
||||||
for _, segment := range sb.block.Segments {
|
|
||||||
wholeSegment = append(wholeSegment, segment...)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h := Helper{
|
h := Helper{
|
||||||
@@ -509,7 +507,7 @@ func (ServerType) extractNamedRoutes(
|
|||||||
route.HandlersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", subroute.CaddyModule().ID.Name(), h.warnings)}
|
route.HandlersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", subroute.CaddyModule().ID.Name(), h.warnings)}
|
||||||
}
|
}
|
||||||
|
|
||||||
namedRoutes[sb.block.Keys[0]] = &route
|
namedRoutes[sb.block.GetKeysText()[0]] = &route
|
||||||
}
|
}
|
||||||
options["named_routes"] = namedRoutes
|
options["named_routes"] = namedRoutes
|
||||||
|
|
||||||
@@ -536,8 +534,8 @@ func (st *ServerType) serversFromPairings(
|
|||||||
if hsp, ok := options["https_port"].(int); ok {
|
if hsp, ok := options["https_port"].(int); ok {
|
||||||
httpsPort = strconv.Itoa(hsp)
|
httpsPort = strconv.Itoa(hsp)
|
||||||
}
|
}
|
||||||
autoHTTPS := "on"
|
autoHTTPS := []string{}
|
||||||
if ah, ok := options["auto_https"].(string); ok {
|
if ah, ok := options["auto_https"].([]string); ok {
|
||||||
autoHTTPS = ah
|
autoHTTPS = ah
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -547,34 +545,86 @@ func (st *ServerType) serversFromPairings(
|
|||||||
// address), otherwise their routes will improperly be added
|
// address), otherwise their routes will improperly be added
|
||||||
// to the same server (see issue #4635)
|
// to the same server (see issue #4635)
|
||||||
for j, sblock1 := range p.serverBlocks {
|
for j, sblock1 := range p.serverBlocks {
|
||||||
for _, key := range sblock1.block.Keys {
|
for _, key := range sblock1.block.GetKeysText() {
|
||||||
for k, sblock2 := range p.serverBlocks {
|
for k, sblock2 := range p.serverBlocks {
|
||||||
if k == j {
|
if k == j {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if sliceContains(sblock2.block.Keys, key) {
|
if slices.Contains(sblock2.block.GetKeysText(), key) {
|
||||||
return nil, fmt.Errorf("ambiguous site definition: %s", key)
|
return nil, fmt.Errorf("ambiguous site definition: %s", key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
addresses []string
|
||||||
|
protocols [][]string
|
||||||
|
)
|
||||||
|
|
||||||
|
for _, addressWithProtocols := range p.addressesWithProtocols {
|
||||||
|
addresses = append(addresses, addressWithProtocols.address)
|
||||||
|
protocols = append(protocols, addressWithProtocols.protocols)
|
||||||
|
}
|
||||||
|
|
||||||
srv := &caddyhttp.Server{
|
srv := &caddyhttp.Server{
|
||||||
Listen: p.addresses,
|
Listen: addresses,
|
||||||
|
ListenProtocols: protocols,
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove srv.ListenProtocols[j] if it only contains the default protocols
|
||||||
|
for j, lnProtocols := range srv.ListenProtocols {
|
||||||
|
srv.ListenProtocols[j] = nil
|
||||||
|
for _, lnProtocol := range lnProtocols {
|
||||||
|
if lnProtocol != "" {
|
||||||
|
srv.ListenProtocols[j] = lnProtocols
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove srv.ListenProtocols if it only contains the default protocols for all listen addresses
|
||||||
|
listenProtocols := srv.ListenProtocols
|
||||||
|
srv.ListenProtocols = nil
|
||||||
|
for _, lnProtocols := range listenProtocols {
|
||||||
|
if lnProtocols != nil {
|
||||||
|
srv.ListenProtocols = listenProtocols
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// handle the auto_https global option
|
// handle the auto_https global option
|
||||||
if autoHTTPS != "on" {
|
for _, val := range autoHTTPS {
|
||||||
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
switch val {
|
||||||
switch autoHTTPS {
|
|
||||||
case "off":
|
case "off":
|
||||||
|
if srv.AutoHTTPS == nil {
|
||||||
|
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||||
|
}
|
||||||
srv.AutoHTTPS.Disabled = true
|
srv.AutoHTTPS.Disabled = true
|
||||||
|
|
||||||
case "disable_redirects":
|
case "disable_redirects":
|
||||||
|
if srv.AutoHTTPS == nil {
|
||||||
|
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||||
|
}
|
||||||
srv.AutoHTTPS.DisableRedir = true
|
srv.AutoHTTPS.DisableRedir = true
|
||||||
|
|
||||||
case "disable_certs":
|
case "disable_certs":
|
||||||
|
if srv.AutoHTTPS == nil {
|
||||||
|
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||||
|
}
|
||||||
srv.AutoHTTPS.DisableCerts = true
|
srv.AutoHTTPS.DisableCerts = true
|
||||||
|
|
||||||
case "ignore_loaded_certs":
|
case "ignore_loaded_certs":
|
||||||
|
if srv.AutoHTTPS == nil {
|
||||||
|
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||||
|
}
|
||||||
srv.AutoHTTPS.IgnoreLoadedCerts = true
|
srv.AutoHTTPS.IgnoreLoadedCerts = true
|
||||||
|
|
||||||
|
case "prefer_wildcard":
|
||||||
|
if srv.AutoHTTPS == nil {
|
||||||
|
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||||
|
}
|
||||||
|
srv.AutoHTTPS.PreferWildcard = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -582,7 +632,7 @@ func (st *ServerType) serversFromPairings(
|
|||||||
// See ParseAddress() where parsing should later reject paths
|
// See ParseAddress() where parsing should later reject paths
|
||||||
// See https://github.com/caddyserver/caddy/pull/4728 for a full explanation
|
// See https://github.com/caddyserver/caddy/pull/4728 for a full explanation
|
||||||
for _, sblock := range p.serverBlocks {
|
for _, sblock := range p.serverBlocks {
|
||||||
for _, addr := range sblock.keys {
|
for _, addr := range sblock.parsedKeys {
|
||||||
if addr.Path != "" {
|
if addr.Path != "" {
|
||||||
caddy.Log().Named("caddyfile").Warn("Using a path in a site address is deprecated; please use the 'handle' directive instead", zap.String("address", addr.String()))
|
caddy.Log().Named("caddyfile").Warn("Using a path in a site address is deprecated; please use the 'handle' directive instead", zap.String("address", addr.String()))
|
||||||
}
|
}
|
||||||
@@ -600,7 +650,7 @@ func (st *ServerType) serversFromPairings(
|
|||||||
var iLongestPath, jLongestPath string
|
var iLongestPath, jLongestPath string
|
||||||
var iLongestHost, jLongestHost string
|
var iLongestHost, jLongestHost string
|
||||||
var iWildcardHost, jWildcardHost bool
|
var iWildcardHost, jWildcardHost bool
|
||||||
for _, addr := range p.serverBlocks[i].keys {
|
for _, addr := range p.serverBlocks[i].parsedKeys {
|
||||||
if strings.Contains(addr.Host, "*") || addr.Host == "" {
|
if strings.Contains(addr.Host, "*") || addr.Host == "" {
|
||||||
iWildcardHost = true
|
iWildcardHost = true
|
||||||
}
|
}
|
||||||
@@ -611,7 +661,7 @@ func (st *ServerType) serversFromPairings(
|
|||||||
iLongestPath = addr.Path
|
iLongestPath = addr.Path
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, addr := range p.serverBlocks[j].keys {
|
for _, addr := range p.serverBlocks[j].parsedKeys {
|
||||||
if strings.Contains(addr.Host, "*") || addr.Host == "" {
|
if strings.Contains(addr.Host, "*") || addr.Host == "" {
|
||||||
jWildcardHost = true
|
jWildcardHost = true
|
||||||
}
|
}
|
||||||
@@ -643,7 +693,7 @@ func (st *ServerType) serversFromPairings(
|
|||||||
})
|
})
|
||||||
|
|
||||||
var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool
|
var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool
|
||||||
autoHTTPSWillAddConnPolicy := autoHTTPS != "off"
|
autoHTTPSWillAddConnPolicy := srv.AutoHTTPS == nil || !srv.AutoHTTPS.Disabled
|
||||||
|
|
||||||
// if needed, the ServerLogConfig is initialized beforehand so
|
// if needed, the ServerLogConfig is initialized beforehand so
|
||||||
// that all server blocks can populate it with data, even when not
|
// that all server blocks can populate it with data, even when not
|
||||||
@@ -710,6 +760,7 @@ func (st *ServerType) serversFromPairings(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(hosts) > 0 {
|
if len(hosts) > 0 {
|
||||||
|
slices.Sort(hosts) // for deterministic JSON output
|
||||||
cp.MatchersRaw = caddy.ModuleMap{
|
cp.MatchersRaw = caddy.ModuleMap{
|
||||||
"sni": caddyconfig.JSON(hosts, warnings), // make sure to match all hosts, not just auto-HTTPS-qualified ones
|
"sni": caddyconfig.JSON(hosts, warnings), // make sure to match all hosts, not just auto-HTTPS-qualified ones
|
||||||
}
|
}
|
||||||
@@ -726,7 +777,14 @@ func (st *ServerType) serversFromPairings(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, addr := range sblock.keys {
|
wildcardHosts := []string{}
|
||||||
|
for _, addr := range sblock.parsedKeys {
|
||||||
|
if strings.HasPrefix(addr.Host, "*.") {
|
||||||
|
wildcardHosts = append(wildcardHosts, addr.Host[2:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, addr := range sblock.parsedKeys {
|
||||||
// if server only uses HTTP port, auto-HTTPS will not apply
|
// if server only uses HTTP port, auto-HTTPS will not apply
|
||||||
if listenersUseAnyPortOtherThan(srv.Listen, httpPort) {
|
if listenersUseAnyPortOtherThan(srv.Listen, httpPort) {
|
||||||
// exclude any hosts that were defined explicitly with "http://"
|
// exclude any hosts that were defined explicitly with "http://"
|
||||||
@@ -735,16 +793,38 @@ func (st *ServerType) serversFromPairings(
|
|||||||
if srv.AutoHTTPS == nil {
|
if srv.AutoHTTPS == nil {
|
||||||
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig)
|
||||||
}
|
}
|
||||||
if !sliceContains(srv.AutoHTTPS.Skip, addr.Host) {
|
if !slices.Contains(srv.AutoHTTPS.Skip, addr.Host) {
|
||||||
srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, addr.Host)
|
srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, addr.Host)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If prefer wildcard is enabled, then we add hosts that are
|
||||||
|
// already covered by the wildcard to the skip list
|
||||||
|
if srv.AutoHTTPS != nil && srv.AutoHTTPS.PreferWildcard && addr.Scheme == "https" {
|
||||||
|
baseDomain := addr.Host
|
||||||
|
if idx := strings.Index(baseDomain, "."); idx != -1 {
|
||||||
|
baseDomain = baseDomain[idx+1:]
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(addr.Host, "*.") && slices.Contains(wildcardHosts, baseDomain) {
|
||||||
|
srv.AutoHTTPS.Skip = append(srv.AutoHTTPS.Skip, addr.Host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If TLS is specified as directive, it will also result in 1 or more connection policy being created
|
||||||
|
// Thus, catch-all address with non-standard port, e.g. :8443, can have TLS enabled without
|
||||||
|
// specifying prefix "https://"
|
||||||
|
// Second part of the condition is to allow creating TLS conn policy even though `auto_https` has been disabled
|
||||||
|
// ensuring compatibility with behavior described in below link
|
||||||
|
// https://caddy.community/t/making-sense-of-auto-https-and-why-disabling-it-still-serves-https-instead-of-http/9761
|
||||||
|
createdTLSConnPolicies, ok := sblock.pile["tls.connection_policy"]
|
||||||
|
hasTLSEnabled := (ok && len(createdTLSConnPolicies) > 0) ||
|
||||||
|
(addr.Host != "" && srv.AutoHTTPS != nil && !slices.Contains(srv.AutoHTTPS.Skip, addr.Host))
|
||||||
|
|
||||||
// we'll need to remember if the address qualifies for auto-HTTPS, so we
|
// we'll need to remember if the address qualifies for auto-HTTPS, so we
|
||||||
// can add a TLS conn policy if necessary
|
// can add a TLS conn policy if necessary
|
||||||
if addr.Scheme == "https" ||
|
if addr.Scheme == "https" ||
|
||||||
(addr.Scheme != "http" && addr.Host != "" && addr.Port != httpPort) {
|
(addr.Scheme != "http" && addr.Port != httpPort && hasTLSEnabled) {
|
||||||
addressQualifiesForTLS = true
|
addressQualifiesForTLS = true
|
||||||
}
|
}
|
||||||
// predict whether auto-HTTPS will add the conn policy for us; if so, we
|
// predict whether auto-HTTPS will add the conn policy for us; if so, we
|
||||||
@@ -782,10 +862,19 @@ func (st *ServerType) serversFromPairings(
|
|||||||
if srv.Errors == nil {
|
if srv.Errors == nil {
|
||||||
srv.Errors = new(caddyhttp.HTTPErrorConfig)
|
srv.Errors = new(caddyhttp.HTTPErrorConfig)
|
||||||
}
|
}
|
||||||
|
sort.SliceStable(errorSubrouteVals, func(i, j int) bool {
|
||||||
|
sri, srj := errorSubrouteVals[i].Value.(*caddyhttp.Subroute), errorSubrouteVals[j].Value.(*caddyhttp.Subroute)
|
||||||
|
if len(sri.Routes[0].MatcherSetsRaw) == 0 && len(srj.Routes[0].MatcherSetsRaw) != 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
errorsSubroute := &caddyhttp.Subroute{}
|
||||||
for _, val := range errorSubrouteVals {
|
for _, val := range errorSubrouteVals {
|
||||||
sr := val.Value.(*caddyhttp.Subroute)
|
sr := val.Value.(*caddyhttp.Subroute)
|
||||||
srv.Errors.Routes = appendSubrouteToRouteList(srv.Errors.Routes, sr, matcherSetsEnc, p, warnings)
|
errorsSubroute.Routes = append(errorsSubroute.Routes, sr.Routes...)
|
||||||
}
|
}
|
||||||
|
srv.Errors.Routes = appendSubrouteToRouteList(srv.Errors.Routes, errorsSubroute, matcherSetsEnc, p, warnings)
|
||||||
}
|
}
|
||||||
|
|
||||||
// add log associations
|
// add log associations
|
||||||
@@ -793,6 +882,15 @@ func (st *ServerType) serversFromPairings(
|
|||||||
sblockLogHosts := sblock.hostsFromKeys(true)
|
sblockLogHosts := sblock.hostsFromKeys(true)
|
||||||
for _, cval := range sblock.pile["custom_log"] {
|
for _, cval := range sblock.pile["custom_log"] {
|
||||||
ncl := cval.Value.(namedCustomLog)
|
ncl := cval.Value.(namedCustomLog)
|
||||||
|
|
||||||
|
// if `no_hostname` is set, then this logger will not
|
||||||
|
// be associated with any of the site block's hostnames,
|
||||||
|
// and only be usable via the `log_name` directive
|
||||||
|
// or the `access_logger_names` variable
|
||||||
|
if ncl.noHostname {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if sblock.hasHostCatchAllKey() && len(ncl.hostnames) == 0 {
|
if sblock.hasHostCatchAllKey() && len(ncl.hostnames) == 0 {
|
||||||
// all requests for hosts not able to be listed should use
|
// all requests for hosts not able to be listed should use
|
||||||
// this log because it's a catch-all-hosts server block
|
// this log because it's a catch-all-hosts server block
|
||||||
@@ -801,17 +899,22 @@ func (st *ServerType) serversFromPairings(
|
|||||||
// if the logger overrides the hostnames, map that to the logger name
|
// if the logger overrides the hostnames, map that to the logger name
|
||||||
for _, h := range ncl.hostnames {
|
for _, h := range ncl.hostnames {
|
||||||
if srv.Logs.LoggerNames == nil {
|
if srv.Logs.LoggerNames == nil {
|
||||||
srv.Logs.LoggerNames = make(map[string]string)
|
srv.Logs.LoggerNames = make(map[string]caddyhttp.StringArray)
|
||||||
}
|
}
|
||||||
srv.Logs.LoggerNames[h] = ncl.name
|
srv.Logs.LoggerNames[h] = append(srv.Logs.LoggerNames[h], ncl.name)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// otherwise, map each host to the logger name
|
// otherwise, map each host to the logger name
|
||||||
for _, h := range sblockLogHosts {
|
for _, h := range sblockLogHosts {
|
||||||
if srv.Logs.LoggerNames == nil {
|
// strip the port from the host, if any
|
||||||
srv.Logs.LoggerNames = make(map[string]string)
|
host, _, err := net.SplitHostPort(h)
|
||||||
|
if err != nil {
|
||||||
|
host = h
|
||||||
}
|
}
|
||||||
srv.Logs.LoggerNames[h] = ncl.name
|
if srv.Logs.LoggerNames == nil {
|
||||||
|
srv.Logs.LoggerNames = make(map[string]caddyhttp.StringArray)
|
||||||
|
}
|
||||||
|
srv.Logs.LoggerNames[host] = append(srv.Logs.LoggerNames[host], ncl.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -828,6 +931,11 @@ func (st *ServerType) serversFromPairings(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sort for deterministic JSON output
|
||||||
|
if srv.Logs != nil {
|
||||||
|
slices.Sort(srv.Logs.SkipHosts)
|
||||||
|
}
|
||||||
|
|
||||||
// a server cannot (natively) serve both HTTP and HTTPS at the
|
// a server cannot (natively) serve both HTTP and HTTPS at the
|
||||||
// same time, so make sure the configuration isn't in conflict
|
// same time, so make sure the configuration isn't in conflict
|
||||||
err := detectConflictingSchemes(srv, p.serverBlocks, options)
|
err := detectConflictingSchemes(srv, p.serverBlocks, options)
|
||||||
@@ -850,7 +958,10 @@ func (st *ServerType) serversFromPairings(
|
|||||||
if addressQualifiesForTLS &&
|
if addressQualifiesForTLS &&
|
||||||
!hasCatchAllTLSConnPolicy &&
|
!hasCatchAllTLSConnPolicy &&
|
||||||
(len(srv.TLSConnPolicies) > 0 || !autoHTTPSWillAddConnPolicy || defaultSNI != "" || fallbackSNI != "") {
|
(len(srv.TLSConnPolicies) > 0 || !autoHTTPSWillAddConnPolicy || defaultSNI != "" || fallbackSNI != "") {
|
||||||
srv.TLSConnPolicies = append(srv.TLSConnPolicies, &caddytls.ConnectionPolicy{DefaultSNI: defaultSNI, FallbackSNI: fallbackSNI})
|
srv.TLSConnPolicies = append(srv.TLSConnPolicies, &caddytls.ConnectionPolicy{
|
||||||
|
DefaultSNI: defaultSNI,
|
||||||
|
FallbackSNI: fallbackSNI,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// tidy things up a bit
|
// tidy things up a bit
|
||||||
@@ -863,8 +974,7 @@ func (st *ServerType) serversFromPairings(
|
|||||||
servers[fmt.Sprintf("srv%d", i)] = srv
|
servers[fmt.Sprintf("srv%d", i)] = srv
|
||||||
}
|
}
|
||||||
|
|
||||||
err := applyServerOptions(servers, options, warnings)
|
if err := applyServerOptions(servers, options, warnings); err != nil {
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("applying global server options: %v", err)
|
return nil, fmt.Errorf("applying global server options: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -909,7 +1019,7 @@ func detectConflictingSchemes(srv *caddyhttp.Server, serverBlocks []serverBlock,
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, sblock := range serverBlocks {
|
for _, sblock := range serverBlocks {
|
||||||
for _, addr := range sblock.keys {
|
for _, addr := range sblock.parsedKeys {
|
||||||
if addr.Scheme == "http" || addr.Port == httpPort {
|
if addr.Scheme == "http" || addr.Port == httpPort {
|
||||||
if err := checkAndSetHTTP(addr); err != nil {
|
if err := checkAndSetHTTP(addr); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -1038,7 +1148,7 @@ func consolidateConnPolicies(cps caddytls.ConnectionPolicies) (caddytls.Connecti
|
|||||||
} else if cps[i].CertSelection != nil && cps[j].CertSelection != nil {
|
} else if cps[i].CertSelection != nil && cps[j].CertSelection != nil {
|
||||||
// if both have one, then combine AnyTag
|
// if both have one, then combine AnyTag
|
||||||
for _, tag := range cps[j].CertSelection.AnyTag {
|
for _, tag := range cps[j].CertSelection.AnyTag {
|
||||||
if !sliceContains(cps[i].CertSelection.AnyTag, tag) {
|
if !slices.Contains(cps[i].CertSelection.AnyTag, tag) {
|
||||||
cps[i].CertSelection.AnyTag = append(cps[i].CertSelection.AnyTag, tag)
|
cps[i].CertSelection.AnyTag = append(cps[i].CertSelection.AnyTag, tag)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1059,8 +1169,8 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList,
|
|||||||
subroute *caddyhttp.Subroute,
|
subroute *caddyhttp.Subroute,
|
||||||
matcherSetsEnc []caddy.ModuleMap,
|
matcherSetsEnc []caddy.ModuleMap,
|
||||||
p sbAddrAssociation,
|
p sbAddrAssociation,
|
||||||
warnings *[]caddyconfig.Warning) caddyhttp.RouteList {
|
warnings *[]caddyconfig.Warning,
|
||||||
|
) caddyhttp.RouteList {
|
||||||
// nothing to do if... there's nothing to do
|
// nothing to do if... there's nothing to do
|
||||||
if len(matcherSetsEnc) == 0 && len(subroute.Routes) == 0 && subroute.Errors == nil {
|
if len(matcherSetsEnc) == 0 && len(subroute.Routes) == 0 && subroute.Errors == nil {
|
||||||
return routeList
|
return routeList
|
||||||
@@ -1121,7 +1231,7 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList,
|
|||||||
func buildSubroute(routes []ConfigValue, groupCounter counter, needsSorting bool) (*caddyhttp.Subroute, error) {
|
func buildSubroute(routes []ConfigValue, groupCounter counter, needsSorting bool) (*caddyhttp.Subroute, error) {
|
||||||
if needsSorting {
|
if needsSorting {
|
||||||
for _, val := range routes {
|
for _, val := range routes {
|
||||||
if !directiveIsOrdered(val.directive) {
|
if !slices.Contains(directiveOrder, val.directive) {
|
||||||
return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global option", val.directive)
|
return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global option", val.directive)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1268,19 +1378,24 @@ func matcherSetFromMatcherToken(
|
|||||||
if tkn.Text == "*" {
|
if tkn.Text == "*" {
|
||||||
// match all requests == no matchers, so nothing to do
|
// match all requests == no matchers, so nothing to do
|
||||||
return nil, true, nil
|
return nil, true, nil
|
||||||
} else if strings.HasPrefix(tkn.Text, "/") {
|
}
|
||||||
|
|
||||||
// convenient way to specify a single path match
|
// convenient way to specify a single path match
|
||||||
|
if strings.HasPrefix(tkn.Text, "/") {
|
||||||
return caddy.ModuleMap{
|
return caddy.ModuleMap{
|
||||||
"path": caddyconfig.JSON(caddyhttp.MatchPath{tkn.Text}, warnings),
|
"path": caddyconfig.JSON(caddyhttp.MatchPath{tkn.Text}, warnings),
|
||||||
}, true, nil
|
}, true, nil
|
||||||
} else if strings.HasPrefix(tkn.Text, matcherPrefix) {
|
}
|
||||||
|
|
||||||
// pre-defined matcher
|
// pre-defined matcher
|
||||||
|
if strings.HasPrefix(tkn.Text, matcherPrefix) {
|
||||||
m, ok := matcherDefs[tkn.Text]
|
m, ok := matcherDefs[tkn.Text]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, false, fmt.Errorf("unrecognized matcher name: %+v", tkn.Text)
|
return nil, false, fmt.Errorf("unrecognized matcher name: %+v", tkn.Text)
|
||||||
}
|
}
|
||||||
return m, true, nil
|
return m, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, false, nil
|
return nil, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1294,7 +1409,7 @@ func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.Mod
|
|||||||
var matcherPairs []*hostPathPair
|
var matcherPairs []*hostPathPair
|
||||||
|
|
||||||
var catchAllHosts bool
|
var catchAllHosts bool
|
||||||
for _, addr := range sblock.keys {
|
for _, addr := range sblock.parsedKeys {
|
||||||
// choose a matcher pair that should be shared by this
|
// choose a matcher pair that should be shared by this
|
||||||
// server block; if none exists yet, create one
|
// server block; if none exists yet, create one
|
||||||
var chosenMatcherPair *hostPathPair
|
var chosenMatcherPair *hostPathPair
|
||||||
@@ -1326,19 +1441,10 @@ func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.Mod
|
|||||||
|
|
||||||
// add this server block's keys to the matcher
|
// add this server block's keys to the matcher
|
||||||
// pair if it doesn't already exist
|
// pair if it doesn't already exist
|
||||||
if addr.Host != "" {
|
if addr.Host != "" && !slices.Contains(chosenMatcherPair.hostm, addr.Host) {
|
||||||
var found bool
|
|
||||||
for _, h := range chosenMatcherPair.hostm {
|
|
||||||
if h == addr.Host {
|
|
||||||
found = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host)
|
chosenMatcherPair.hostm = append(chosenMatcherPair.hostm, addr.Host)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// iterate each pairing of host and path matchers and
|
// iterate each pairing of host and path matchers and
|
||||||
// put them into a map for JSON encoding
|
// put them into a map for JSON encoding
|
||||||
@@ -1370,7 +1476,8 @@ func (st *ServerType) compileEncodedMatcherSets(sblock serverBlock) ([]caddy.Mod
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.ModuleMap) error {
|
func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.ModuleMap) error {
|
||||||
for d.Next() {
|
d.Next() // advance to the first token
|
||||||
|
|
||||||
// this is the "name" for "named matchers"
|
// this is the "name" for "named matchers"
|
||||||
definitionName := d.Val()
|
definitionName := d.Val()
|
||||||
|
|
||||||
@@ -1382,6 +1489,14 @@ func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.M
|
|||||||
// given a matcher name and the tokens following it, parse
|
// given a matcher name and the tokens following it, parse
|
||||||
// the tokens as a matcher module and record it
|
// the tokens as a matcher module and record it
|
||||||
makeMatcher := func(matcherName string, tokens []caddyfile.Token) error {
|
makeMatcher := func(matcherName string, tokens []caddyfile.Token) error {
|
||||||
|
// create a new dispenser from the tokens
|
||||||
|
dispenser := caddyfile.NewDispenser(tokens)
|
||||||
|
|
||||||
|
// set the matcher name (without @) in the dispenser context so
|
||||||
|
// that matcher modules can access it to use it as their name
|
||||||
|
// (e.g. regexp matchers which use the name for capture groups)
|
||||||
|
dispenser.SetContext(caddyfile.MatcherNameCtxKey, definitionName[1:])
|
||||||
|
|
||||||
mod, err := caddy.GetModule("http.matchers." + matcherName)
|
mod, err := caddy.GetModule("http.matchers." + matcherName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("getting matcher module '%s': %v", matcherName, err)
|
return fmt.Errorf("getting matcher module '%s': %v", matcherName, err)
|
||||||
@@ -1390,7 +1505,7 @@ func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.M
|
|||||||
if !ok {
|
if !ok {
|
||||||
return fmt.Errorf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName)
|
return fmt.Errorf("matcher module '%s' is not a Caddyfile unmarshaler", matcherName)
|
||||||
}
|
}
|
||||||
err = unm.UnmarshalCaddyfile(caddyfile.NewDispenser(tokens))
|
err = unm.UnmarshalCaddyfile(dispenser)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1406,11 +1521,18 @@ func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.M
|
|||||||
// and that it's probably an 'expression' matcher
|
// and that it's probably an 'expression' matcher
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
if d.Token().Quoted() {
|
if d.Token().Quoted() {
|
||||||
err := makeMatcher("expression", []caddyfile.Token{d.Token()})
|
// since it was missing the matcher name, we insert a token
|
||||||
|
// in front of the expression token itself; we use Clone() to
|
||||||
|
// make the new token to keep the same the import location as
|
||||||
|
// the next token, if this is within a snippet or imported file.
|
||||||
|
// see https://github.com/caddyserver/caddy/issues/6287
|
||||||
|
expressionToken := d.Token().Clone()
|
||||||
|
expressionToken.Text = "expression"
|
||||||
|
err := makeMatcher("expression", []caddyfile.Token{expressionToken, d.Token()})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
continue
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// if it wasn't quoted, then we need to rewind after calling
|
// if it wasn't quoted, then we need to rewind after calling
|
||||||
@@ -1433,7 +1555,6 @@ func parseMatcherDefinitions(d *caddyfile.Dispenser, matchers map[string]caddy.M
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1449,37 +1570,6 @@ func encodeMatcherSet(matchers map[string]caddyhttp.RequestMatcher) (caddy.Modul
|
|||||||
return msEncoded, nil
|
return msEncoded, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// placeholderShorthands returns a slice of old-new string pairs,
|
|
||||||
// where the left of the pair is a placeholder shorthand that may
|
|
||||||
// be used in the Caddyfile, and the right is the replacement.
|
|
||||||
func placeholderShorthands() []string {
|
|
||||||
return []string{
|
|
||||||
"{dir}", "{http.request.uri.path.dir}",
|
|
||||||
"{file}", "{http.request.uri.path.file}",
|
|
||||||
"{host}", "{http.request.host}",
|
|
||||||
"{hostport}", "{http.request.hostport}",
|
|
||||||
"{port}", "{http.request.port}",
|
|
||||||
"{method}", "{http.request.method}",
|
|
||||||
"{path}", "{http.request.uri.path}",
|
|
||||||
"{query}", "{http.request.uri.query}",
|
|
||||||
"{remote}", "{http.request.remote}",
|
|
||||||
"{remote_host}", "{http.request.remote.host}",
|
|
||||||
"{remote_port}", "{http.request.remote.port}",
|
|
||||||
"{scheme}", "{http.request.scheme}",
|
|
||||||
"{uri}", "{http.request.uri}",
|
|
||||||
"{tls_cipher}", "{http.request.tls.cipher_suite}",
|
|
||||||
"{tls_version}", "{http.request.tls.version}",
|
|
||||||
"{tls_client_fingerprint}", "{http.request.tls.client.fingerprint}",
|
|
||||||
"{tls_client_issuer}", "{http.request.tls.client.issuer}",
|
|
||||||
"{tls_client_serial}", "{http.request.tls.client.serial}",
|
|
||||||
"{tls_client_subject}", "{http.request.tls.client.subject}",
|
|
||||||
"{tls_client_certificate_pem}", "{http.request.tls.client.certificate_pem}",
|
|
||||||
"{tls_client_certificate_der_base64}", "{http.request.tls.client.certificate_der_base64}",
|
|
||||||
"{upstream_hostport}", "{http.reverse_proxy.upstream.hostport}",
|
|
||||||
"{client_ip}", "{http.vars.client_ip}",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WasReplacedPlaceholderShorthand checks if a token string was
|
// WasReplacedPlaceholderShorthand checks if a token string was
|
||||||
// likely a replaced shorthand of the known Caddyfile placeholder
|
// likely a replaced shorthand of the known Caddyfile placeholder
|
||||||
// replacement outputs. Useful to prevent some user-defined map
|
// replacement outputs. Useful to prevent some user-defined map
|
||||||
@@ -1528,16 +1618,6 @@ func tryDuration(val any, warnings *[]caddyconfig.Warning) caddy.Duration {
|
|||||||
return durationVal
|
return durationVal
|
||||||
}
|
}
|
||||||
|
|
||||||
// sliceContains returns true if needle is in haystack.
|
|
||||||
func sliceContains(haystack []string, needle string) bool {
|
|
||||||
for _, s := range haystack {
|
|
||||||
if s == needle {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// listenersUseAnyPortOtherThan returns true if there are any
|
// listenersUseAnyPortOtherThan returns true if there are any
|
||||||
// listeners in addresses that use a port which is not otherPort.
|
// listeners in addresses that use a port which is not otherPort.
|
||||||
// Mostly borrowed from unexported method in caddyhttp package.
|
// Mostly borrowed from unexported method in caddyhttp package.
|
||||||
@@ -1598,18 +1678,28 @@ type namedCustomLog struct {
|
|||||||
name string
|
name string
|
||||||
hostnames []string
|
hostnames []string
|
||||||
log *caddy.CustomLog
|
log *caddy.CustomLog
|
||||||
|
noHostname bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// addressWithProtocols associates a listen address with
|
||||||
|
// the protocols to serve it with
|
||||||
|
type addressWithProtocols struct {
|
||||||
|
address string
|
||||||
|
protocols []string
|
||||||
}
|
}
|
||||||
|
|
||||||
// sbAddrAssociation is a mapping from a list of
|
// sbAddrAssociation is a mapping from a list of
|
||||||
// addresses to a list of server blocks that are
|
// addresses with protocols, and a list of server
|
||||||
// served on those addresses.
|
// blocks that are served on those addresses.
|
||||||
type sbAddrAssociation struct {
|
type sbAddrAssociation struct {
|
||||||
addresses []string
|
addressesWithProtocols []addressWithProtocols
|
||||||
serverBlocks []serverBlock
|
serverBlocks []serverBlock
|
||||||
}
|
}
|
||||||
|
|
||||||
const matcherPrefix = "@"
|
const (
|
||||||
const namedRouteKey = "named_route"
|
matcherPrefix = "@"
|
||||||
|
namedRouteKey = "named_route"
|
||||||
|
)
|
||||||
|
|
||||||
// Interface guard
|
// Interface guard
|
||||||
var _ caddyfile.ServerType = (*ServerType)(nil)
|
var _ caddyfile.ServerType = (*ServerType)(nil)
|
||||||
|
|||||||
@@ -15,21 +15,23 @@
|
|||||||
package httpcaddyfile
|
package httpcaddyfile
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/caddyserver/certmagic"
|
||||||
|
"github.com/mholt/acmez/v2/acme"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
"github.com/caddyserver/caddy/v2"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||||
"github.com/caddyserver/certmagic"
|
|
||||||
"github.com/mholt/acmez/acme"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
RegisterGlobalOption("debug", parseOptTrue)
|
RegisterGlobalOption("debug", parseOptTrue)
|
||||||
RegisterGlobalOption("http_port", parseOptHTTPPort)
|
RegisterGlobalOption("http_port", parseOptHTTPPort)
|
||||||
RegisterGlobalOption("https_port", parseOptHTTPSPort)
|
RegisterGlobalOption("https_port", parseOptHTTPSPort)
|
||||||
RegisterGlobalOption("default_bind", parseOptStringList)
|
RegisterGlobalOption("default_bind", parseOptDefaultBind)
|
||||||
RegisterGlobalOption("grace_period", parseOptDuration)
|
RegisterGlobalOption("grace_period", parseOptDuration)
|
||||||
RegisterGlobalOption("shutdown_delay", parseOptDuration)
|
RegisterGlobalOption("shutdown_delay", parseOptDuration)
|
||||||
RegisterGlobalOption("default_sni", parseOptSingleString)
|
RegisterGlobalOption("default_sni", parseOptSingleString)
|
||||||
@@ -53,6 +55,7 @@ func init() {
|
|||||||
RegisterGlobalOption("auto_https", parseOptAutoHTTPS)
|
RegisterGlobalOption("auto_https", parseOptAutoHTTPS)
|
||||||
RegisterGlobalOption("servers", parseServerOptions)
|
RegisterGlobalOption("servers", parseServerOptions)
|
||||||
RegisterGlobalOption("ocsp_stapling", parseOCSPStaplingOptions)
|
RegisterGlobalOption("ocsp_stapling", parseOCSPStaplingOptions)
|
||||||
|
RegisterGlobalOption("cert_lifetime", parseOptDuration)
|
||||||
RegisterGlobalOption("log", parseLogOptions)
|
RegisterGlobalOption("log", parseLogOptions)
|
||||||
RegisterGlobalOption("preferred_chains", parseOptPreferredChains)
|
RegisterGlobalOption("preferred_chains", parseOptPreferredChains)
|
||||||
RegisterGlobalOption("persist_config", parseOptPersistConfig)
|
RegisterGlobalOption("persist_config", parseOptPersistConfig)
|
||||||
@@ -61,8 +64,8 @@ func init() {
|
|||||||
func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil }
|
func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil }
|
||||||
|
|
||||||
func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
|
d.Next() // consume option name
|
||||||
var httpPort int
|
var httpPort int
|
||||||
for d.Next() {
|
|
||||||
var httpPortStr string
|
var httpPortStr string
|
||||||
if !d.AllArgs(&httpPortStr) {
|
if !d.AllArgs(&httpPortStr) {
|
||||||
return 0, d.ArgErr()
|
return 0, d.ArgErr()
|
||||||
@@ -72,13 +75,12 @@ func parseOptHTTPPort(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, d.Errf("converting port '%s' to integer value: %v", httpPortStr, err)
|
return 0, d.Errf("converting port '%s' to integer value: %v", httpPortStr, err)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return httpPort, nil
|
return httpPort, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptHTTPSPort(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptHTTPSPort(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
|
d.Next() // consume option name
|
||||||
var httpsPort int
|
var httpsPort int
|
||||||
for d.Next() {
|
|
||||||
var httpsPortStr string
|
var httpsPortStr string
|
||||||
if !d.AllArgs(&httpsPortStr) {
|
if !d.AllArgs(&httpsPortStr) {
|
||||||
return 0, d.ArgErr()
|
return 0, d.ArgErr()
|
||||||
@@ -88,14 +90,12 @@ func parseOptHTTPSPort(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, d.Errf("converting port '%s' to integer value: %v", httpsPortStr, err)
|
return 0, d.Errf("converting port '%s' to integer value: %v", httpsPortStr, err)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return httpsPort, nil
|
return httpsPort, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
newOrder := directiveOrder
|
d.Next() // consume option name
|
||||||
|
|
||||||
for d.Next() {
|
|
||||||
// get directive name
|
// get directive name
|
||||||
if !d.Next() {
|
if !d.Next() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
@@ -109,34 +109,35 @@ func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
if !d.Next() {
|
if !d.Next() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
pos := d.Val()
|
pos := Positional(d.Val())
|
||||||
|
|
||||||
// if directive exists, first remove it
|
// if directive already had an order, drop it
|
||||||
for i, d := range newOrder {
|
newOrder := slices.DeleteFunc(directiveOrder, func(d string) bool {
|
||||||
if d == dirName {
|
return d == dirName
|
||||||
newOrder = append(newOrder[:i], newOrder[i+1:]...)
|
})
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// act on the positional
|
// act on the positional; if it's First or Last, we're done right away
|
||||||
switch pos {
|
switch pos {
|
||||||
case "first":
|
case First:
|
||||||
newOrder = append([]string{dirName}, newOrder...)
|
newOrder = append([]string{dirName}, newOrder...)
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
directiveOrder = newOrder
|
directiveOrder = newOrder
|
||||||
return newOrder, nil
|
return newOrder, nil
|
||||||
case "last":
|
|
||||||
|
case Last:
|
||||||
newOrder = append(newOrder, dirName)
|
newOrder = append(newOrder, dirName)
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
directiveOrder = newOrder
|
directiveOrder = newOrder
|
||||||
return newOrder, nil
|
return newOrder, nil
|
||||||
case "before":
|
|
||||||
case "after":
|
// if it's Before or After, continue
|
||||||
|
case Before:
|
||||||
|
case After:
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nil, d.Errf("unknown positional '%s'", pos)
|
return nil, d.Errf("unknown positional '%s'", pos)
|
||||||
}
|
}
|
||||||
@@ -150,18 +151,17 @@ func parseOptOrder(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
|
|
||||||
// insert directive into proper position
|
// get the position of the target directive
|
||||||
for i, d := range newOrder {
|
targetIndex := slices.Index(newOrder, otherDir)
|
||||||
if d == otherDir {
|
if targetIndex == -1 {
|
||||||
if pos == "before" {
|
return nil, d.Errf("directive '%s' not found", otherDir)
|
||||||
newOrder = append(newOrder[:i], append([]string{dirName}, newOrder[i:]...)...)
|
|
||||||
} else if pos == "after" {
|
|
||||||
newOrder = append(newOrder[:i+1], append([]string{dirName}, newOrder[i+1:]...)...)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// if we're inserting after, we need to increment the index to go after
|
||||||
|
if pos == After {
|
||||||
|
targetIndex++
|
||||||
}
|
}
|
||||||
|
// insert the directive into the new order
|
||||||
|
newOrder = slices.Insert(newOrder, targetIndex, dirName)
|
||||||
|
|
||||||
directiveOrder = newOrder
|
directiveOrder = newOrder
|
||||||
|
|
||||||
@@ -213,20 +213,20 @@ func parseOptACMEDNS(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
prov, ok := unm.(certmagic.ACMEDNSProvider)
|
prov, ok := unm.(certmagic.DNSProvider)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, d.Errf("module %s (%T) is not a certmagic.ACMEDNSProvider", modID, unm)
|
return nil, d.Errf("module %s (%T) is not a certmagic.DNSProvider", modID, unm)
|
||||||
}
|
}
|
||||||
return prov, nil
|
return prov, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptACMEEAB(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptACMEEAB(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
eab := new(acme.EAB)
|
eab := new(acme.EAB)
|
||||||
for d.Next() {
|
d.Next() // consume option name
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
for d.NextBlock(0) {
|
||||||
switch d.Val() {
|
switch d.Val() {
|
||||||
case "key_id":
|
case "key_id":
|
||||||
if !d.NextArg() {
|
if !d.NextArg() {
|
||||||
@@ -244,17 +244,19 @@ func parseOptACMEEAB(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
|
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return eab, nil
|
return eab, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptCertIssuer(d *caddyfile.Dispenser, existing any) (any, error) {
|
func parseOptCertIssuer(d *caddyfile.Dispenser, existing any) (any, error) {
|
||||||
|
d.Next() // consume option name
|
||||||
|
|
||||||
var issuers []certmagic.Issuer
|
var issuers []certmagic.Issuer
|
||||||
if existing != nil {
|
if existing != nil {
|
||||||
issuers = existing.([]certmagic.Issuer)
|
issuers = existing.([]certmagic.Issuer)
|
||||||
}
|
}
|
||||||
for d.Next() { // consume option name
|
|
||||||
if !d.Next() { // get issuer module name
|
// get issuer module name
|
||||||
|
if !d.Next() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
modID := "tls.issuance." + d.Val()
|
modID := "tls.issuance." + d.Val()
|
||||||
@@ -267,12 +269,11 @@ func parseOptCertIssuer(d *caddyfile.Dispenser, existing any) (any, error) {
|
|||||||
return nil, d.Errf("module %s (%T) is not a certmagic.Issuer", modID, unm)
|
return nil, d.Errf("module %s (%T) is not a certmagic.Issuer", modID, unm)
|
||||||
}
|
}
|
||||||
issuers = append(issuers, iss)
|
issuers = append(issuers, iss)
|
||||||
}
|
|
||||||
return issuers, nil
|
return issuers, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptSingleString(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptSingleString(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
d.Next() // consume parameter name
|
d.Next() // consume option name
|
||||||
if !d.Next() {
|
if !d.Next() {
|
||||||
return "", d.ArgErr()
|
return "", d.ArgErr()
|
||||||
}
|
}
|
||||||
@@ -283,18 +284,38 @@ func parseOptSingleString(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
return val, nil
|
return val, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptStringList(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptDefaultBind(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
d.Next() // consume parameter name
|
d.Next() // consume option name
|
||||||
val := d.RemainingArgs()
|
|
||||||
if len(val) == 0 {
|
var addresses, protocols []string
|
||||||
return "", d.ArgErr()
|
addresses = d.RemainingArgs()
|
||||||
|
|
||||||
|
if len(addresses) == 0 {
|
||||||
|
addresses = append(addresses, "")
|
||||||
}
|
}
|
||||||
return val, nil
|
|
||||||
|
for d.NextBlock(0) {
|
||||||
|
switch d.Val() {
|
||||||
|
case "protocols":
|
||||||
|
protocols = d.RemainingArgs()
|
||||||
|
if len(protocols) == 0 {
|
||||||
|
return nil, d.Errf("protocols requires one or more arguments")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, d.Errf("unknown subdirective: %s", d.Val())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return []ConfigValue{{Class: "bind", Value: addressesWithProtocols{
|
||||||
|
addresses: addresses,
|
||||||
|
protocols: protocols,
|
||||||
|
}}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
|
d.Next() // consume option name
|
||||||
|
|
||||||
adminCfg := new(caddy.AdminConfig)
|
adminCfg := new(caddy.AdminConfig)
|
||||||
for d.Next() {
|
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
listenAddress := d.Val()
|
listenAddress := d.Val()
|
||||||
if listenAddress == "off" {
|
if listenAddress == "off" {
|
||||||
@@ -309,7 +330,7 @@ func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
for d.NextBlock(0) {
|
||||||
switch d.Val() {
|
switch d.Val() {
|
||||||
case "enforce_origin":
|
case "enforce_origin":
|
||||||
adminCfg.EnforceOrigin = true
|
adminCfg.EnforceOrigin = true
|
||||||
@@ -321,7 +342,6 @@ func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
|
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if adminCfg.Listen == "" && !adminCfg.Disabled {
|
if adminCfg.Listen == "" && !adminCfg.Disabled {
|
||||||
adminCfg.Listen = caddy.DefaultAdminListen
|
adminCfg.Listen = caddy.DefaultAdminListen
|
||||||
}
|
}
|
||||||
@@ -329,11 +349,13 @@ func parseOptAdmin(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
var ond *caddytls.OnDemandConfig
|
d.Next() // consume option name
|
||||||
for d.Next() {
|
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var ond *caddytls.OnDemandConfig
|
||||||
|
|
||||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||||
switch d.Val() {
|
switch d.Val() {
|
||||||
case "ask":
|
case "ask":
|
||||||
@@ -343,45 +365,44 @@ func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
if ond == nil {
|
if ond == nil {
|
||||||
ond = new(caddytls.OnDemandConfig)
|
ond = new(caddytls.OnDemandConfig)
|
||||||
}
|
}
|
||||||
ond.Ask = d.Val()
|
if ond.PermissionRaw != nil {
|
||||||
|
return nil, d.Err("on-demand TLS permission module (or 'ask') already specified")
|
||||||
|
}
|
||||||
|
perm := caddytls.PermissionByHTTP{Endpoint: d.Val()}
|
||||||
|
ond.PermissionRaw = caddyconfig.JSONModuleObject(perm, "module", "http", nil)
|
||||||
|
|
||||||
|
case "permission":
|
||||||
|
if !d.NextArg() {
|
||||||
|
return nil, d.ArgErr()
|
||||||
|
}
|
||||||
|
if ond == nil {
|
||||||
|
ond = new(caddytls.OnDemandConfig)
|
||||||
|
}
|
||||||
|
if ond.PermissionRaw != nil {
|
||||||
|
return nil, d.Err("on-demand TLS permission module (or 'ask') already specified")
|
||||||
|
}
|
||||||
|
modName := d.Val()
|
||||||
|
modID := "tls.permission." + modName
|
||||||
|
unm, err := caddyfile.UnmarshalModule(d, modID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
perm, ok := unm.(caddytls.OnDemandPermission)
|
||||||
|
if !ok {
|
||||||
|
return nil, d.Errf("module %s (%T) is not an on-demand TLS permission module", modID, unm)
|
||||||
|
}
|
||||||
|
ond.PermissionRaw = caddyconfig.JSONModuleObject(perm, "module", modName, nil)
|
||||||
|
|
||||||
case "interval":
|
case "interval":
|
||||||
if !d.NextArg() {
|
return nil, d.Errf("the on_demand_tls 'interval' option is no longer supported, remove it from your config")
|
||||||
return nil, d.ArgErr()
|
|
||||||
}
|
|
||||||
dur, err := caddy.ParseDuration(d.Val())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if ond == nil {
|
|
||||||
ond = new(caddytls.OnDemandConfig)
|
|
||||||
}
|
|
||||||
if ond.RateLimit == nil {
|
|
||||||
ond.RateLimit = new(caddytls.RateLimit)
|
|
||||||
}
|
|
||||||
ond.RateLimit.Interval = caddy.Duration(dur)
|
|
||||||
|
|
||||||
case "burst":
|
case "burst":
|
||||||
if !d.NextArg() {
|
return nil, d.Errf("the on_demand_tls 'burst' option is no longer supported, remove it from your config")
|
||||||
return nil, d.ArgErr()
|
|
||||||
}
|
|
||||||
burst, err := strconv.Atoi(d.Val())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if ond == nil {
|
|
||||||
ond = new(caddytls.OnDemandConfig)
|
|
||||||
}
|
|
||||||
if ond.RateLimit == nil {
|
|
||||||
ond.RateLimit = new(caddytls.RateLimit)
|
|
||||||
}
|
|
||||||
ond.RateLimit.Burst = burst
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
|
return nil, d.Errf("unrecognized parameter '%s'", d.Val())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if ond == nil {
|
if ond == nil {
|
||||||
return nil, d.Err("expected at least one config parameter for on_demand_tls")
|
return nil, d.Err("expected at least one config parameter for on_demand_tls")
|
||||||
}
|
}
|
||||||
@@ -389,7 +410,7 @@ func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseOptPersistConfig(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptPersistConfig(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
d.Next() // consume parameter name
|
d.Next() // consume option name
|
||||||
if !d.Next() {
|
if !d.Next() {
|
||||||
return "", d.ArgErr()
|
return "", d.ArgErr()
|
||||||
}
|
}
|
||||||
@@ -404,16 +425,23 @@ func parseOptPersistConfig(d *caddyfile.Dispenser, _ any) (any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ any) (any, error) {
|
func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||||
d.Next() // consume parameter name
|
d.Next() // consume option name
|
||||||
if !d.Next() {
|
val := d.RemainingArgs()
|
||||||
|
if len(val) == 0 {
|
||||||
return "", d.ArgErr()
|
return "", d.ArgErr()
|
||||||
}
|
}
|
||||||
val := d.Val()
|
for _, v := range val {
|
||||||
if d.Next() {
|
switch v {
|
||||||
return "", d.ArgErr()
|
case "off":
|
||||||
|
case "disable_redirects":
|
||||||
|
case "disable_certs":
|
||||||
|
case "ignore_loaded_certs":
|
||||||
|
case "prefer_wildcard":
|
||||||
|
break
|
||||||
|
|
||||||
|
default:
|
||||||
|
return "", d.Errf("auto_https must be one of 'off', 'disable_redirects', 'disable_certs', 'ignore_loaded_certs', or 'prefer_wildcard'")
|
||||||
}
|
}
|
||||||
if val != "off" && val != "disable_redirects" && val != "disable_certs" && val != "ignore_loaded_certs" {
|
|
||||||
return "", d.Errf("auto_https must be one of 'off', 'disable_redirects', 'disable_certs', or 'ignore_loaded_certs'")
|
|
||||||
}
|
}
|
||||||
return val, nil
|
return val, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,10 +48,12 @@ func init() {
|
|||||||
//
|
//
|
||||||
// When the CA ID is unspecified, 'local' is assumed.
|
// When the CA ID is unspecified, 'local' is assumed.
|
||||||
func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) {
|
func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) {
|
||||||
pki := &caddypki.PKI{CAs: make(map[string]*caddypki.CA)}
|
d.Next() // consume app name
|
||||||
|
|
||||||
for d.Next() {
|
pki := &caddypki.PKI{
|
||||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
CAs: make(map[string]*caddypki.CA),
|
||||||
|
}
|
||||||
|
for d.NextBlock(0) {
|
||||||
switch d.Val() {
|
switch d.Val() {
|
||||||
case "ca":
|
case "ca":
|
||||||
pkiCa := new(caddypki.CA)
|
pkiCa := new(caddypki.CA)
|
||||||
@@ -164,8 +166,6 @@ func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) {
|
|||||||
return nil, d.Errf("unrecognized pki option '%s'", d.Val())
|
return nil, d.Errf("unrecognized pki option '%s'", d.Val())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return pki, nil
|
return pki, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,7 +174,6 @@ func (st ServerType) buildPKIApp(
|
|||||||
options map[string]any,
|
options map[string]any,
|
||||||
warnings []caddyconfig.Warning,
|
warnings []caddyconfig.Warning,
|
||||||
) (*caddypki.PKI, []caddyconfig.Warning, error) {
|
) (*caddypki.PKI, []caddyconfig.Warning, error) {
|
||||||
|
|
||||||
skipInstallTrust := false
|
skipInstallTrust := false
|
||||||
if _, ok := options["skip_install_trust"]; ok {
|
if _, ok := options["skip_install_trust"]; ok {
|
||||||
skipInstallTrust = true
|
skipInstallTrust = true
|
||||||
|
|||||||
@@ -17,12 +17,14 @@ package httpcaddyfile
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
"github.com/dustin/go-humanize"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
"github.com/caddyserver/caddy/v2"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/dustin/go-humanize"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// serverOptions collects server config overrides parsed from Caddyfile global options
|
// serverOptions collects server config overrides parsed from Caddyfile global options
|
||||||
@@ -45,21 +47,24 @@ type serverOptions struct {
|
|||||||
Protocols []string
|
Protocols []string
|
||||||
StrictSNIHost *bool
|
StrictSNIHost *bool
|
||||||
TrustedProxiesRaw json.RawMessage
|
TrustedProxiesRaw json.RawMessage
|
||||||
|
TrustedProxiesStrict int
|
||||||
ClientIPHeaders []string
|
ClientIPHeaders []string
|
||||||
ShouldLogCredentials bool
|
ShouldLogCredentials bool
|
||||||
Metrics *caddyhttp.Metrics
|
Metrics *caddyhttp.Metrics
|
||||||
|
Trace bool // TODO: EXPERIMENTAL
|
||||||
}
|
}
|
||||||
|
|
||||||
func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
||||||
|
d.Next() // consume option name
|
||||||
|
|
||||||
serverOpts := serverOptions{}
|
serverOpts := serverOptions{}
|
||||||
for d.Next() {
|
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
serverOpts.ListenerAddress = d.Val()
|
serverOpts.ListenerAddress = d.Val()
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
for d.NextBlock(0) {
|
||||||
switch d.Val() {
|
switch d.Val() {
|
||||||
case "name":
|
case "name":
|
||||||
if serverOpts.ListenerAddress == "" {
|
if serverOpts.ListenerAddress == "" {
|
||||||
@@ -176,7 +181,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
|||||||
if proto != "h1" && proto != "h2" && proto != "h2c" && proto != "h3" {
|
if proto != "h1" && proto != "h2" && proto != "h2c" && proto != "h3" {
|
||||||
return nil, d.Errf("unknown protocol '%s': expected h1, h2, h2c, or h3", proto)
|
return nil, d.Errf("unknown protocol '%s': expected h1, h2, h2c, or h3", proto)
|
||||||
}
|
}
|
||||||
if sliceContains(serverOpts.Protocols, proto) {
|
if slices.Contains(serverOpts.Protocols, proto) {
|
||||||
return nil, d.Errf("protocol %s specified more than once", proto)
|
return nil, d.Errf("protocol %s specified more than once", proto)
|
||||||
}
|
}
|
||||||
serverOpts.Protocols = append(serverOpts.Protocols, proto)
|
serverOpts.Protocols = append(serverOpts.Protocols, proto)
|
||||||
@@ -216,10 +221,16 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
|||||||
)
|
)
|
||||||
serverOpts.TrustedProxiesRaw = jsonSource
|
serverOpts.TrustedProxiesRaw = jsonSource
|
||||||
|
|
||||||
|
case "trusted_proxies_strict":
|
||||||
|
if d.NextArg() {
|
||||||
|
return nil, d.ArgErr()
|
||||||
|
}
|
||||||
|
serverOpts.TrustedProxiesStrict = 1
|
||||||
|
|
||||||
case "client_ip_headers":
|
case "client_ip_headers":
|
||||||
headers := d.RemainingArgs()
|
headers := d.RemainingArgs()
|
||||||
for _, header := range headers {
|
for _, header := range headers {
|
||||||
if sliceContains(serverOpts.ClientIPHeaders, header) {
|
if slices.Contains(serverOpts.ClientIPHeaders, header) {
|
||||||
return nil, d.Errf("client IP header %s specified more than once", header)
|
return nil, d.Errf("client IP header %s specified more than once", header)
|
||||||
}
|
}
|
||||||
serverOpts.ClientIPHeaders = append(serverOpts.ClientIPHeaders, header)
|
serverOpts.ClientIPHeaders = append(serverOpts.ClientIPHeaders, header)
|
||||||
@@ -229,53 +240,24 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "metrics":
|
case "metrics":
|
||||||
if d.NextArg() {
|
|
||||||
return nil, d.ArgErr()
|
|
||||||
}
|
|
||||||
if nesting := d.Nesting(); d.NextBlock(nesting) {
|
|
||||||
return nil, d.ArgErr()
|
|
||||||
}
|
|
||||||
serverOpts.Metrics = new(caddyhttp.Metrics)
|
serverOpts.Metrics = new(caddyhttp.Metrics)
|
||||||
|
|
||||||
// TODO: DEPRECATED. (August 2022)
|
|
||||||
case "protocol":
|
|
||||||
caddy.Log().Named("caddyfile").Warn("DEPRECATED: protocol sub-option will be removed soon")
|
|
||||||
|
|
||||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||||
switch d.Val() {
|
switch d.Val() {
|
||||||
case "allow_h2c":
|
case "per_host":
|
||||||
caddy.Log().Named("caddyfile").Warn("DEPRECATED: allow_h2c will be removed soon; use protocols option instead")
|
serverOpts.Metrics.PerHost = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "trace":
|
||||||
if d.NextArg() {
|
if d.NextArg() {
|
||||||
return nil, d.ArgErr()
|
return nil, d.ArgErr()
|
||||||
}
|
}
|
||||||
if sliceContains(serverOpts.Protocols, "h2c") {
|
serverOpts.Trace = true
|
||||||
return nil, d.Errf("protocol h2c already specified")
|
|
||||||
}
|
|
||||||
serverOpts.Protocols = append(serverOpts.Protocols, "h2c")
|
|
||||||
|
|
||||||
case "strict_sni_host":
|
|
||||||
caddy.Log().Named("caddyfile").Warn("DEPRECATED: protocol > strict_sni_host in this position will be removed soon; move up to the servers block instead")
|
|
||||||
|
|
||||||
if d.NextArg() && d.Val() != "insecure_off" && d.Val() != "on" {
|
|
||||||
return nil, d.Errf("strict_sni_host only supports 'on' or 'insecure_off', got '%s'", d.Val())
|
|
||||||
}
|
|
||||||
boolVal := true
|
|
||||||
if d.Val() == "insecure_off" {
|
|
||||||
boolVal = false
|
|
||||||
}
|
|
||||||
serverOpts.StrictSNIHost = &boolVal
|
|
||||||
|
|
||||||
default:
|
|
||||||
return nil, d.Errf("unrecognized protocol option '%s'", d.Val())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nil, d.Errf("unrecognized servers option '%s'", d.Val())
|
return nil, d.Errf("unrecognized servers option '%s'", d.Val())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return serverOpts, nil
|
return serverOpts, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,7 +265,7 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
|||||||
func applyServerOptions(
|
func applyServerOptions(
|
||||||
servers map[string]*caddyhttp.Server,
|
servers map[string]*caddyhttp.Server,
|
||||||
options map[string]any,
|
options map[string]any,
|
||||||
warnings *[]caddyconfig.Warning,
|
_ *[]caddyconfig.Warning,
|
||||||
) error {
|
) error {
|
||||||
serverOpts, ok := options["servers"].([]serverOptions)
|
serverOpts, ok := options["servers"].([]serverOptions)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -307,24 +289,15 @@ func applyServerOptions(
|
|||||||
|
|
||||||
for key, server := range servers {
|
for key, server := range servers {
|
||||||
// find the options that apply to this server
|
// find the options that apply to this server
|
||||||
opts := func() *serverOptions {
|
optsIndex := slices.IndexFunc(serverOpts, func(s serverOptions) bool {
|
||||||
for _, entry := range serverOpts {
|
return s.ListenerAddress == "" || slices.Contains(server.Listen, s.ListenerAddress)
|
||||||
if entry.ListenerAddress == "" {
|
})
|
||||||
return &entry
|
|
||||||
}
|
|
||||||
for _, listener := range server.Listen {
|
|
||||||
if entry.ListenerAddress == listener {
|
|
||||||
return &entry
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}()
|
|
||||||
|
|
||||||
// if none apply, then move to the next server
|
// if none apply, then move to the next server
|
||||||
if opts == nil {
|
if optsIndex == -1 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
opts := serverOpts[optsIndex]
|
||||||
|
|
||||||
// set all the options
|
// set all the options
|
||||||
server.ListenerWrappersRaw = opts.ListenerWrappersRaw
|
server.ListenerWrappersRaw = opts.ListenerWrappersRaw
|
||||||
@@ -339,13 +312,21 @@ func applyServerOptions(
|
|||||||
server.StrictSNIHost = opts.StrictSNIHost
|
server.StrictSNIHost = opts.StrictSNIHost
|
||||||
server.TrustedProxiesRaw = opts.TrustedProxiesRaw
|
server.TrustedProxiesRaw = opts.TrustedProxiesRaw
|
||||||
server.ClientIPHeaders = opts.ClientIPHeaders
|
server.ClientIPHeaders = opts.ClientIPHeaders
|
||||||
|
server.TrustedProxiesStrict = opts.TrustedProxiesStrict
|
||||||
server.Metrics = opts.Metrics
|
server.Metrics = opts.Metrics
|
||||||
if opts.ShouldLogCredentials {
|
if opts.ShouldLogCredentials {
|
||||||
if server.Logs == nil {
|
if server.Logs == nil {
|
||||||
server.Logs = &caddyhttp.ServerLogConfig{}
|
server.Logs = new(caddyhttp.ServerLogConfig)
|
||||||
}
|
}
|
||||||
server.Logs.ShouldLogCredentials = opts.ShouldLogCredentials
|
server.Logs.ShouldLogCredentials = opts.ShouldLogCredentials
|
||||||
}
|
}
|
||||||
|
if opts.Trace {
|
||||||
|
// TODO: THIS IS EXPERIMENTAL (MAY 2024)
|
||||||
|
if server.Logs == nil {
|
||||||
|
server.Logs = new(caddyhttp.ServerLogConfig)
|
||||||
|
}
|
||||||
|
server.Logs.Trace = opts.Trace
|
||||||
|
}
|
||||||
|
|
||||||
if opts.Name != "" {
|
if opts.Name != "" {
|
||||||
nameReplacements[key] = opts.Name
|
nameReplacements[key] = opts.Name
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package httpcaddyfile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ComplexShorthandReplacer struct {
|
||||||
|
search *regexp.Regexp
|
||||||
|
replace string
|
||||||
|
}
|
||||||
|
|
||||||
|
type ShorthandReplacer struct {
|
||||||
|
complex []ComplexShorthandReplacer
|
||||||
|
simple *strings.Replacer
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewShorthandReplacer() ShorthandReplacer {
|
||||||
|
// replace shorthand placeholders (which are convenient
|
||||||
|
// when writing a Caddyfile) with their actual placeholder
|
||||||
|
// identifiers or variable names
|
||||||
|
replacer := strings.NewReplacer(placeholderShorthands()...)
|
||||||
|
|
||||||
|
// these are placeholders that allow a user-defined final
|
||||||
|
// parameters, but we still want to provide a shorthand
|
||||||
|
// for those, so we use a regexp to replace
|
||||||
|
regexpReplacements := []ComplexShorthandReplacer{
|
||||||
|
{regexp.MustCompile(`{header\.([\w-]*)}`), "{http.request.header.$1}"},
|
||||||
|
{regexp.MustCompile(`{cookie\.([\w-]*)}`), "{http.request.cookie.$1}"},
|
||||||
|
{regexp.MustCompile(`{labels\.([\w-]*)}`), "{http.request.host.labels.$1}"},
|
||||||
|
{regexp.MustCompile(`{path\.([\w-]*)}`), "{http.request.uri.path.$1}"},
|
||||||
|
{regexp.MustCompile(`{file\.([\w-]*)}`), "{http.request.uri.path.file.$1}"},
|
||||||
|
{regexp.MustCompile(`{query\.([\w-]*)}`), "{http.request.uri.query.$1}"},
|
||||||
|
{regexp.MustCompile(`{re\.([\w-\.]*)}`), "{http.regexp.$1}"},
|
||||||
|
{regexp.MustCompile(`{vars\.([\w-]*)}`), "{http.vars.$1}"},
|
||||||
|
{regexp.MustCompile(`{rp\.([\w-\.]*)}`), "{http.reverse_proxy.$1}"},
|
||||||
|
{regexp.MustCompile(`{resp\.([\w-\.]*)}`), "{http.intercept.$1}"},
|
||||||
|
{regexp.MustCompile(`{err\.([\w-\.]*)}`), "{http.error.$1}"},
|
||||||
|
{regexp.MustCompile(`{file_match\.([\w-]*)}`), "{http.matchers.file.$1}"},
|
||||||
|
}
|
||||||
|
|
||||||
|
return ShorthandReplacer{
|
||||||
|
complex: regexpReplacements,
|
||||||
|
simple: replacer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// placeholderShorthands returns a slice of old-new string pairs,
|
||||||
|
// where the left of the pair is a placeholder shorthand that may
|
||||||
|
// be used in the Caddyfile, and the right is the replacement.
|
||||||
|
func placeholderShorthands() []string {
|
||||||
|
return []string{
|
||||||
|
"{dir}", "{http.request.uri.path.dir}",
|
||||||
|
"{file}", "{http.request.uri.path.file}",
|
||||||
|
"{host}", "{http.request.host}",
|
||||||
|
"{hostport}", "{http.request.hostport}",
|
||||||
|
"{port}", "{http.request.port}",
|
||||||
|
"{method}", "{http.request.method}",
|
||||||
|
"{path}", "{http.request.uri.path}",
|
||||||
|
"{query}", "{http.request.uri.query}",
|
||||||
|
"{remote}", "{http.request.remote}",
|
||||||
|
"{remote_host}", "{http.request.remote.host}",
|
||||||
|
"{remote_port}", "{http.request.remote.port}",
|
||||||
|
"{scheme}", "{http.request.scheme}",
|
||||||
|
"{uri}", "{http.request.uri}",
|
||||||
|
"{uuid}", "{http.request.uuid}",
|
||||||
|
"{tls_cipher}", "{http.request.tls.cipher_suite}",
|
||||||
|
"{tls_version}", "{http.request.tls.version}",
|
||||||
|
"{tls_client_fingerprint}", "{http.request.tls.client.fingerprint}",
|
||||||
|
"{tls_client_issuer}", "{http.request.tls.client.issuer}",
|
||||||
|
"{tls_client_serial}", "{http.request.tls.client.serial}",
|
||||||
|
"{tls_client_subject}", "{http.request.tls.client.subject}",
|
||||||
|
"{tls_client_certificate_pem}", "{http.request.tls.client.certificate_pem}",
|
||||||
|
"{tls_client_certificate_der_base64}", "{http.request.tls.client.certificate_der_base64}",
|
||||||
|
"{upstream_hostport}", "{http.reverse_proxy.upstream.hostport}",
|
||||||
|
"{client_ip}", "{http.vars.client_ip}",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyToSegment replaces shorthand placeholder to its full placeholder, understandable by Caddy.
|
||||||
|
func (s ShorthandReplacer) ApplyToSegment(segment *caddyfile.Segment) {
|
||||||
|
if segment != nil {
|
||||||
|
for i := 0; i < len(*segment); i++ {
|
||||||
|
// simple string replacements
|
||||||
|
(*segment)[i].Text = s.simple.Replace((*segment)[i].Text)
|
||||||
|
// complex regexp replacements
|
||||||
|
for _, r := range s.complex {
|
||||||
|
(*segment)[i].Text = r.search.ReplaceAllString((*segment)[i].Text, r.replace)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,16 +19,18 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/caddyserver/certmagic"
|
||||||
|
"github.com/mholt/acmez/v2/acme"
|
||||||
|
|
||||||
"github.com/caddyserver/caddy/v2"
|
"github.com/caddyserver/caddy/v2"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
||||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||||
"github.com/caddyserver/certmagic"
|
|
||||||
"github.com/mholt/acmez/acme"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (st ServerType) buildTLSApp(
|
func (st ServerType) buildTLSApp(
|
||||||
@@ -36,7 +38,6 @@ func (st ServerType) buildTLSApp(
|
|||||||
options map[string]any,
|
options map[string]any,
|
||||||
warnings []caddyconfig.Warning,
|
warnings []caddyconfig.Warning,
|
||||||
) (*caddytls.TLS, []caddyconfig.Warning, error) {
|
) (*caddytls.TLS, []caddyconfig.Warning, error) {
|
||||||
|
|
||||||
tlsApp := &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)}
|
tlsApp := &caddytls.TLS{CertificatesRaw: make(caddy.ModuleMap)}
|
||||||
var certLoaders []caddytls.CertificateLoader
|
var certLoaders []caddytls.CertificateLoader
|
||||||
|
|
||||||
@@ -44,8 +45,8 @@ func (st ServerType) buildTLSApp(
|
|||||||
if hp, ok := options["http_port"].(int); ok {
|
if hp, ok := options["http_port"].(int); ok {
|
||||||
httpPort = strconv.Itoa(hp)
|
httpPort = strconv.Itoa(hp)
|
||||||
}
|
}
|
||||||
autoHTTPS := "on"
|
autoHTTPS := []string{}
|
||||||
if ah, ok := options["auto_https"].(string); ok {
|
if ah, ok := options["auto_https"].([]string); ok {
|
||||||
autoHTTPS = ah
|
autoHTTPS = ah
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,14 +54,17 @@ func (st ServerType) buildTLSApp(
|
|||||||
// key, so that they don't get forgotten/omitted by auto-HTTPS
|
// key, so that they don't get forgotten/omitted by auto-HTTPS
|
||||||
// (since they won't appear in route matchers)
|
// (since they won't appear in route matchers)
|
||||||
httpsHostsSharedWithHostlessKey := make(map[string]struct{})
|
httpsHostsSharedWithHostlessKey := make(map[string]struct{})
|
||||||
if autoHTTPS != "off" {
|
if !slices.Contains(autoHTTPS, "off") {
|
||||||
for _, pair := range pairings {
|
for _, pair := range pairings {
|
||||||
for _, sb := range pair.serverBlocks {
|
for _, sb := range pair.serverBlocks {
|
||||||
for _, addr := range sb.keys {
|
for _, addr := range sb.parsedKeys {
|
||||||
if addr.Host == "" {
|
if addr.Host != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
// this server block has a hostless key, now
|
// this server block has a hostless key, now
|
||||||
// go through and add all the hosts to the set
|
// go through and add all the hosts to the set
|
||||||
for _, otherAddr := range sb.keys {
|
for _, otherAddr := range sb.parsedKeys {
|
||||||
if otherAddr.Original == addr.Original {
|
if otherAddr.Original == addr.Original {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -73,7 +77,6 @@ func (st ServerType) buildTLSApp(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// a catch-all automation policy is used as a "default" for all subjects that
|
// a catch-all automation policy is used as a "default" for all subjects that
|
||||||
// don't have custom configuration explicitly associated with them; this
|
// don't have custom configuration explicitly associated with them; this
|
||||||
@@ -91,7 +94,11 @@ func (st ServerType) buildTLSApp(
|
|||||||
|
|
||||||
for _, p := range pairings {
|
for _, p := range pairings {
|
||||||
// avoid setting up TLS automation policies for a server that is HTTP-only
|
// avoid setting up TLS automation policies for a server that is HTTP-only
|
||||||
if !listenersUseAnyPortOtherThan(p.addresses, httpPort) {
|
var addresses []string
|
||||||
|
for _, addressWithProtocols := range p.addressesWithProtocols {
|
||||||
|
addresses = append(addresses, addressWithProtocols.address)
|
||||||
|
}
|
||||||
|
if !listenersUseAnyPortOtherThan(addresses, httpPort) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +125,11 @@ func (st ServerType) buildTLSApp(
|
|||||||
ap.OnDemand = true
|
ap.OnDemand = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reuse private keys tls
|
||||||
|
if _, ok := sblock.pile["tls.reuse_private_keys"]; ok {
|
||||||
|
ap.ReusePrivateKeys = true
|
||||||
|
}
|
||||||
|
|
||||||
if keyTypeVals, ok := sblock.pile["tls.key_type"]; ok {
|
if keyTypeVals, ok := sblock.pile["tls.key_type"]; ok {
|
||||||
ap.KeyType = keyTypeVals[0].Value.(string)
|
ap.KeyType = keyTypeVals[0].Value.(string)
|
||||||
}
|
}
|
||||||
@@ -176,8 +188,8 @@ func (st ServerType) buildTLSApp(
|
|||||||
if acmeIssuer.Challenges.BindHost == "" {
|
if acmeIssuer.Challenges.BindHost == "" {
|
||||||
// only binding to one host is supported
|
// only binding to one host is supported
|
||||||
var bindHost string
|
var bindHost string
|
||||||
if bindHosts, ok := cfgVal.Value.([]string); ok && len(bindHosts) > 0 {
|
if asserted, ok := cfgVal.Value.(addressesWithProtocols); ok && len(asserted.addresses) > 0 {
|
||||||
bindHost = bindHosts[0]
|
bindHost = asserted.addresses[0]
|
||||||
}
|
}
|
||||||
acmeIssuer.Challenges.BindHost = bindHost
|
acmeIssuer.Challenges.BindHost = bindHost
|
||||||
}
|
}
|
||||||
@@ -219,7 +231,7 @@ func (st ServerType) buildTLSApp(
|
|||||||
var internal, external []string
|
var internal, external []string
|
||||||
for _, s := range ap.SubjectsRaw {
|
for _, s := range ap.SubjectsRaw {
|
||||||
// do not create Issuers for Tailscale domains; they will be given a Manager instead
|
// do not create Issuers for Tailscale domains; they will be given a Manager instead
|
||||||
if strings.HasSuffix(strings.ToLower(s), ".ts.net") {
|
if isTailscaleDomain(s) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !certmagic.SubjectQualifiesForCert(s) {
|
if !certmagic.SubjectQualifiesForCert(s) {
|
||||||
@@ -339,7 +351,7 @@ func (st ServerType) buildTLSApp(
|
|||||||
internalAP := &caddytls.AutomationPolicy{
|
internalAP := &caddytls.AutomationPolicy{
|
||||||
IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
|
IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
|
||||||
}
|
}
|
||||||
if autoHTTPS != "off" {
|
if !slices.Contains(autoHTTPS, "off") && !slices.Contains(autoHTTPS, "disable_certs") {
|
||||||
for h := range httpsHostsSharedWithHostlessKey {
|
for h := range httpsHostsSharedWithHostlessKey {
|
||||||
al = append(al, h)
|
al = append(al, h)
|
||||||
if !certmagic.SubjectQualifiesForPublicCert(h) {
|
if !certmagic.SubjectQualifiesForPublicCert(h) {
|
||||||
@@ -373,20 +385,17 @@ func (st ServerType) buildTLSApp(
|
|||||||
if len(ap.Issuers) == 0 && automationPolicyHasAllPublicNames(ap) {
|
if len(ap.Issuers) == 0 && automationPolicyHasAllPublicNames(ap) {
|
||||||
// for public names, create default issuers which will later be filled in with configured global defaults
|
// for public names, create default issuers which will later be filled in with configured global defaults
|
||||||
// (internal names will implicitly use the internal issuer at auto-https time)
|
// (internal names will implicitly use the internal issuer at auto-https time)
|
||||||
ap.Issuers = caddytls.DefaultIssuers()
|
emailStr, _ := globalEmail.(string)
|
||||||
|
ap.Issuers = caddytls.DefaultIssuers(emailStr)
|
||||||
|
|
||||||
// if a specific endpoint is configured, can't use multiple default issuers
|
// if a specific endpoint is configured, can't use multiple default issuers
|
||||||
if globalACMECA != nil {
|
if globalACMECA != nil {
|
||||||
if strings.Contains(globalACMECA.(string), "zerossl") {
|
|
||||||
ap.Issuers = []certmagic.Issuer{&caddytls.ZeroSSLIssuer{ACMEIssuer: new(caddytls.ACMEIssuer)}}
|
|
||||||
} else {
|
|
||||||
ap.Issuers = []certmagic.Issuer{new(caddytls.ACMEIssuer)}
|
ap.Issuers = []certmagic.Issuer{new(caddytls.ACMEIssuer)}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// finalize and verify policies; do cleanup
|
// finalize and verify policies; do cleanup
|
||||||
if tlsApp.Automation != nil {
|
if tlsApp.Automation != nil {
|
||||||
@@ -409,7 +418,10 @@ func (st ServerType) buildTLSApp(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// consolidate automation policies that are the exact same
|
// consolidate automation policies that are the exact same
|
||||||
tlsApp.Automation.Policies = consolidateAutomationPolicies(tlsApp.Automation.Policies)
|
tlsApp.Automation.Policies = consolidateAutomationPolicies(
|
||||||
|
tlsApp.Automation.Policies,
|
||||||
|
slices.Contains(autoHTTPS, "prefer_wildcard"),
|
||||||
|
)
|
||||||
|
|
||||||
// ensure automation policies don't overlap subjects (this should be
|
// ensure automation policies don't overlap subjects (this should be
|
||||||
// an error at provision-time as well, but catch it in the adapt phase
|
// an error at provision-time as well, but catch it in the adapt phase
|
||||||
@@ -454,6 +466,8 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e
|
|||||||
globalACMEDNS := options["acme_dns"]
|
globalACMEDNS := options["acme_dns"]
|
||||||
globalACMEEAB := options["acme_eab"]
|
globalACMEEAB := options["acme_eab"]
|
||||||
globalPreferredChains := options["preferred_chains"]
|
globalPreferredChains := options["preferred_chains"]
|
||||||
|
globalCertLifetime := options["cert_lifetime"]
|
||||||
|
globalHTTPPort, globalHTTPSPort := options["http_port"], options["https_port"]
|
||||||
|
|
||||||
if globalEmail != nil && acmeIssuer.Email == "" {
|
if globalEmail != nil && acmeIssuer.Email == "" {
|
||||||
acmeIssuer.Email = globalEmail.(string)
|
acmeIssuer.Email = globalEmail.(string)
|
||||||
@@ -461,7 +475,7 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e
|
|||||||
if globalACMECA != nil && acmeIssuer.CA == "" {
|
if globalACMECA != nil && acmeIssuer.CA == "" {
|
||||||
acmeIssuer.CA = globalACMECA.(string)
|
acmeIssuer.CA = globalACMECA.(string)
|
||||||
}
|
}
|
||||||
if globalACMECARoot != nil && !sliceContains(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) {
|
if globalACMECARoot != nil && !slices.Contains(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string)) {
|
||||||
acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string))
|
acmeIssuer.TrustedRootsPEMFiles = append(acmeIssuer.TrustedRootsPEMFiles, globalACMECARoot.(string))
|
||||||
}
|
}
|
||||||
if globalACMEDNS != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil) {
|
if globalACMEDNS != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.DNS == nil) {
|
||||||
@@ -477,6 +491,27 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e
|
|||||||
if globalPreferredChains != nil && acmeIssuer.PreferredChains == nil {
|
if globalPreferredChains != nil && acmeIssuer.PreferredChains == nil {
|
||||||
acmeIssuer.PreferredChains = globalPreferredChains.(*caddytls.ChainPreference)
|
acmeIssuer.PreferredChains = globalPreferredChains.(*caddytls.ChainPreference)
|
||||||
}
|
}
|
||||||
|
if globalHTTPPort != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.HTTP == nil || acmeIssuer.Challenges.HTTP.AlternatePort == 0) {
|
||||||
|
if acmeIssuer.Challenges == nil {
|
||||||
|
acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
|
||||||
|
}
|
||||||
|
if acmeIssuer.Challenges.HTTP == nil {
|
||||||
|
acmeIssuer.Challenges.HTTP = new(caddytls.HTTPChallengeConfig)
|
||||||
|
}
|
||||||
|
acmeIssuer.Challenges.HTTP.AlternatePort = globalHTTPPort.(int)
|
||||||
|
}
|
||||||
|
if globalHTTPSPort != nil && (acmeIssuer.Challenges == nil || acmeIssuer.Challenges.TLSALPN == nil || acmeIssuer.Challenges.TLSALPN.AlternatePort == 0) {
|
||||||
|
if acmeIssuer.Challenges == nil {
|
||||||
|
acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
|
||||||
|
}
|
||||||
|
if acmeIssuer.Challenges.TLSALPN == nil {
|
||||||
|
acmeIssuer.Challenges.TLSALPN = new(caddytls.TLSALPNChallengeConfig)
|
||||||
|
}
|
||||||
|
acmeIssuer.Challenges.TLSALPN.AlternatePort = globalHTTPSPort.(int)
|
||||||
|
}
|
||||||
|
if globalCertLifetime != nil && acmeIssuer.CertificateLifetime == 0 {
|
||||||
|
acmeIssuer.CertificateLifetime = globalCertLifetime.(caddy.Duration)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -485,7 +520,11 @@ func fillInGlobalACMEDefaults(issuer certmagic.Issuer, options map[string]any) e
|
|||||||
// for any other automation policies. A nil policy (and no error) will be
|
// for any other automation policies. A nil policy (and no error) will be
|
||||||
// returned if there are no default/global options. However, if always is
|
// returned if there are no default/global options. However, if always is
|
||||||
// true, a non-nil value will always be returned (unless there is an error).
|
// true, a non-nil value will always be returned (unless there is an error).
|
||||||
func newBaseAutomationPolicy(options map[string]any, warnings []caddyconfig.Warning, always bool) (*caddytls.AutomationPolicy, error) {
|
func newBaseAutomationPolicy(
|
||||||
|
options map[string]any,
|
||||||
|
_ []caddyconfig.Warning,
|
||||||
|
always bool,
|
||||||
|
) (*caddytls.AutomationPolicy, error) {
|
||||||
issuers, hasIssuers := options["cert_issuer"]
|
issuers, hasIssuers := options["cert_issuer"]
|
||||||
_, hasLocalCerts := options["local_certs"]
|
_, hasLocalCerts := options["local_certs"]
|
||||||
keyType, hasKeyType := options["key_type"]
|
keyType, hasKeyType := options["key_type"]
|
||||||
@@ -528,7 +567,7 @@ func newBaseAutomationPolicy(options map[string]any, warnings []caddyconfig.Warn
|
|||||||
|
|
||||||
// consolidateAutomationPolicies combines automation policies that are the same,
|
// consolidateAutomationPolicies combines automation policies that are the same,
|
||||||
// for a cleaner overall output.
|
// for a cleaner overall output.
|
||||||
func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls.AutomationPolicy {
|
func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy, preferWildcard bool) []*caddytls.AutomationPolicy {
|
||||||
// sort from most specific to least specific; we depend on this ordering
|
// sort from most specific to least specific; we depend on this ordering
|
||||||
sort.SliceStable(aps, func(i, j int) bool {
|
sort.SliceStable(aps, func(i, j int) bool {
|
||||||
if automationPolicyIsSubset(aps[i], aps[j]) {
|
if automationPolicyIsSubset(aps[i], aps[j]) {
|
||||||
@@ -551,7 +590,7 @@ func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls
|
|||||||
if !automationPolicyHasAllPublicNames(aps[i]) {
|
if !automationPolicyHasAllPublicNames(aps[i]) {
|
||||||
// if this automation policy has internal names, we might as well remove it
|
// if this automation policy has internal names, we might as well remove it
|
||||||
// so auto-https can implicitly use the internal issuer
|
// so auto-https can implicitly use the internal issuer
|
||||||
aps = append(aps[:i], aps[i+1:]...)
|
aps = slices.Delete(aps, i, i+1)
|
||||||
i--
|
i--
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -568,7 +607,7 @@ outer:
|
|||||||
for j := i + 1; j < len(aps); j++ {
|
for j := i + 1; j < len(aps); j++ {
|
||||||
// if they're exactly equal in every way, just keep one of them
|
// if they're exactly equal in every way, just keep one of them
|
||||||
if reflect.DeepEqual(aps[i], aps[j]) {
|
if reflect.DeepEqual(aps[i], aps[j]) {
|
||||||
aps = append(aps[:j], aps[j+1:]...)
|
aps = slices.Delete(aps, j, j+1)
|
||||||
// must re-evaluate current i against next j; can't skip it!
|
// must re-evaluate current i against next j; can't skip it!
|
||||||
// even if i decrements to -1, will be incremented to 0 immediately
|
// even if i decrements to -1, will be incremented to 0 immediately
|
||||||
i--
|
i--
|
||||||
@@ -582,10 +621,12 @@ outer:
|
|||||||
// eaten up by the one with subjects; and if both have subjects, we
|
// eaten up by the one with subjects; and if both have subjects, we
|
||||||
// need to combine their lists
|
// need to combine their lists
|
||||||
if reflect.DeepEqual(aps[i].IssuersRaw, aps[j].IssuersRaw) &&
|
if reflect.DeepEqual(aps[i].IssuersRaw, aps[j].IssuersRaw) &&
|
||||||
|
reflect.DeepEqual(aps[i].ManagersRaw, aps[j].ManagersRaw) &&
|
||||||
bytes.Equal(aps[i].StorageRaw, aps[j].StorageRaw) &&
|
bytes.Equal(aps[i].StorageRaw, aps[j].StorageRaw) &&
|
||||||
aps[i].MustStaple == aps[j].MustStaple &&
|
aps[i].MustStaple == aps[j].MustStaple &&
|
||||||
aps[i].KeyType == aps[j].KeyType &&
|
aps[i].KeyType == aps[j].KeyType &&
|
||||||
aps[i].OnDemand == aps[j].OnDemand &&
|
aps[i].OnDemand == aps[j].OnDemand &&
|
||||||
|
aps[i].ReusePrivateKeys == aps[j].ReusePrivateKeys &&
|
||||||
aps[i].RenewalWindowRatio == aps[j].RenewalWindowRatio {
|
aps[i].RenewalWindowRatio == aps[j].RenewalWindowRatio {
|
||||||
if len(aps[i].SubjectsRaw) > 0 && len(aps[j].SubjectsRaw) == 0 {
|
if len(aps[i].SubjectsRaw) > 0 && len(aps[j].SubjectsRaw) == 0 {
|
||||||
// later policy (at j) has no subjects ("catch-all"), so we can
|
// later policy (at j) has no subjects ("catch-all"), so we can
|
||||||
@@ -596,21 +637,46 @@ outer:
|
|||||||
// cause example.com to be served by the less specific policy for
|
// cause example.com to be served by the less specific policy for
|
||||||
// '*.com', which might be different (yes we've seen this happen)
|
// '*.com', which might be different (yes we've seen this happen)
|
||||||
if automationPolicyShadows(i, aps) >= j {
|
if automationPolicyShadows(i, aps) >= j {
|
||||||
aps = append(aps[:i], aps[i+1:]...)
|
aps = slices.Delete(aps, i, i+1)
|
||||||
i--
|
i--
|
||||||
continue outer
|
continue outer
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// avoid repeated subjects
|
// avoid repeated subjects
|
||||||
for _, subj := range aps[j].SubjectsRaw {
|
for _, subj := range aps[j].SubjectsRaw {
|
||||||
if !sliceContains(aps[i].SubjectsRaw, subj) {
|
if !slices.Contains(aps[i].SubjectsRaw, subj) {
|
||||||
aps[i].SubjectsRaw = append(aps[i].SubjectsRaw, subj)
|
aps[i].SubjectsRaw = append(aps[i].SubjectsRaw, subj)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
aps = append(aps[:j], aps[j+1:]...)
|
aps = slices.Delete(aps, j, j+1)
|
||||||
j--
|
j--
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if preferWildcard {
|
||||||
|
// remove subjects from i if they're covered by a wildcard in j
|
||||||
|
iSubjs := aps[i].SubjectsRaw
|
||||||
|
for iSubj := 0; iSubj < len(iSubjs); iSubj++ {
|
||||||
|
for jSubj := range aps[j].SubjectsRaw {
|
||||||
|
if !strings.HasPrefix(aps[j].SubjectsRaw[jSubj], "*.") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if certmagic.MatchWildcard(aps[i].SubjectsRaw[iSubj], aps[j].SubjectsRaw[jSubj]) {
|
||||||
|
iSubjs = slices.Delete(iSubjs, iSubj, iSubj+1)
|
||||||
|
iSubj--
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
aps[i].SubjectsRaw = iSubjs
|
||||||
|
|
||||||
|
// remove i if it has no subjects left
|
||||||
|
if len(aps[i].SubjectsRaw) == 0 {
|
||||||
|
aps = slices.Delete(aps, i, i+1)
|
||||||
|
i--
|
||||||
|
continue outer
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -627,13 +693,9 @@ func automationPolicyIsSubset(a, b *caddytls.AutomationPolicy) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for _, aSubj := range a.SubjectsRaw {
|
for _, aSubj := range a.SubjectsRaw {
|
||||||
var inSuperset bool
|
inSuperset := slices.ContainsFunc(b.SubjectsRaw, func(bSubj string) bool {
|
||||||
for _, bSubj := range b.SubjectsRaw {
|
return certmagic.MatchWildcard(aSubj, bSubj)
|
||||||
if certmagic.MatchWildcard(aSubj, bSubj) {
|
})
|
||||||
inSuperset = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !inSuperset {
|
if !inSuperset {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -659,17 +721,30 @@ func automationPolicyShadows(i int, aps []*caddytls.AutomationPolicy) int {
|
|||||||
// subjectQualifiesForPublicCert is like certmagic.SubjectQualifiesForPublicCert() except
|
// subjectQualifiesForPublicCert is like certmagic.SubjectQualifiesForPublicCert() except
|
||||||
// that this allows domains with multiple wildcard levels like '*.*.example.com' to qualify
|
// that this allows domains with multiple wildcard levels like '*.*.example.com' to qualify
|
||||||
// if the automation policy has OnDemand enabled (i.e. this function is more lenient).
|
// if the automation policy has OnDemand enabled (i.e. this function is more lenient).
|
||||||
|
//
|
||||||
|
// IP subjects are considered as non-qualifying for public certs. Technically, there are
|
||||||
|
// now public ACME CAs as well as non-ACME CAs that issue IP certificates. But this function
|
||||||
|
// is used solely for implicit automation (defaults), where it gets really complicated to
|
||||||
|
// keep track of which issuers support IP certificates in which circumstances. Currently,
|
||||||
|
// issuers that support IP certificates are very few, and all require some sort of config
|
||||||
|
// from the user anyway (such as an account credential). Since we cannot implicitly and
|
||||||
|
// automatically get public IP certs without configuration from the user, we treat IPs as
|
||||||
|
// not qualifying for public certificates. Users should expressly configure an issuer
|
||||||
|
// that supports IP certs for that purpose.
|
||||||
func subjectQualifiesForPublicCert(ap *caddytls.AutomationPolicy, subj string) bool {
|
func subjectQualifiesForPublicCert(ap *caddytls.AutomationPolicy, subj string) bool {
|
||||||
return !certmagic.SubjectIsIP(subj) &&
|
return !certmagic.SubjectIsIP(subj) &&
|
||||||
!certmagic.SubjectIsInternal(subj) &&
|
!certmagic.SubjectIsInternal(subj) &&
|
||||||
(strings.Count(subj, "*.") < 2 || ap.OnDemand)
|
(strings.Count(subj, "*.") < 2 || ap.OnDemand)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// automationPolicyHasAllPublicNames returns true if all the names on the policy
|
||||||
|
// do NOT qualify for public certs OR are tailscale domains.
|
||||||
func automationPolicyHasAllPublicNames(ap *caddytls.AutomationPolicy) bool {
|
func automationPolicyHasAllPublicNames(ap *caddytls.AutomationPolicy) bool {
|
||||||
for _, subj := range ap.SubjectsRaw {
|
return !slices.ContainsFunc(ap.SubjectsRaw, func(i string) bool {
|
||||||
if !subjectQualifiesForPublicCert(ap, subj) {
|
return !subjectQualifiesForPublicCert(ap, i) || isTailscaleDomain(i)
|
||||||
return false
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return true
|
func isTailscaleDomain(name string) bool {
|
||||||
|
return strings.HasSuffix(strings.ToLower(name), ".ts.net")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -181,19 +181,16 @@ func (hl HTTPLoader) makeClient(ctx caddy.Context) (*http.Client, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("getting server identity credentials: %v", err)
|
return nil, fmt.Errorf("getting server identity credentials: %v", err)
|
||||||
}
|
}
|
||||||
if tlsConfig == nil {
|
// See https://github.com/securego/gosec/issues/1054#issuecomment-2072235199
|
||||||
tlsConfig = new(tls.Config)
|
//nolint:gosec
|
||||||
}
|
tlsConfig = &tls.Config{Certificates: certs}
|
||||||
tlsConfig.Certificates = certs
|
|
||||||
} else if hl.TLS.ClientCertificateFile != "" && hl.TLS.ClientCertificateKeyFile != "" {
|
} else if hl.TLS.ClientCertificateFile != "" && hl.TLS.ClientCertificateKeyFile != "" {
|
||||||
cert, err := tls.LoadX509KeyPair(hl.TLS.ClientCertificateFile, hl.TLS.ClientCertificateKeyFile)
|
cert, err := tls.LoadX509KeyPair(hl.TLS.ClientCertificateFile, hl.TLS.ClientCertificateKeyFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if tlsConfig == nil {
|
//nolint:gosec
|
||||||
tlsConfig = new(tls.Config)
|
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||||
}
|
|
||||||
tlsConfig.Certificates = []tls.Certificate{cert}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// trusted server certs
|
// trusted server certs
|
||||||
|
|||||||
+28
-29
@@ -8,6 +8,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -22,9 +23,10 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/aryann/difflib"
|
"github.com/aryann/difflib"
|
||||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
|
||||||
caddycmd "github.com/caddyserver/caddy/v2/cmd"
|
caddycmd "github.com/caddyserver/caddy/v2/cmd"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||||
// plug in Caddy modules here
|
// plug in Caddy modules here
|
||||||
_ "github.com/caddyserver/caddy/v2/modules/standard"
|
_ "github.com/caddyserver/caddy/v2/modules/standard"
|
||||||
)
|
)
|
||||||
@@ -34,7 +36,7 @@ type Defaults struct {
|
|||||||
// Port we expect caddy to listening on
|
// Port we expect caddy to listening on
|
||||||
AdminPort int
|
AdminPort int
|
||||||
// Certificates we expect to be loaded before attempting to run the tests
|
// Certificates we expect to be loaded before attempting to run the tests
|
||||||
Certifcates []string
|
Certificates []string
|
||||||
// TestRequestTimeout is the time to wait for a http request to
|
// TestRequestTimeout is the time to wait for a http request to
|
||||||
TestRequestTimeout time.Duration
|
TestRequestTimeout time.Duration
|
||||||
// LoadRequestTimeout is the time to wait for the config to be loaded against the caddy server
|
// LoadRequestTimeout is the time to wait for the config to be loaded against the caddy server
|
||||||
@@ -44,7 +46,7 @@ type Defaults struct {
|
|||||||
// Default testing values
|
// Default testing values
|
||||||
var Default = Defaults{
|
var Default = Defaults{
|
||||||
AdminPort: 2999, // different from what a real server also running on a developer's machine might be
|
AdminPort: 2999, // different from what a real server also running on a developer's machine might be
|
||||||
Certifcates: []string{"/caddy.localhost.crt", "/caddy.localhost.key"},
|
Certificates: []string{"/caddy.localhost.crt", "/caddy.localhost.key"},
|
||||||
TestRequestTimeout: 5 * time.Second,
|
TestRequestTimeout: 5 * time.Second,
|
||||||
LoadRequestTimeout: 5 * time.Second,
|
LoadRequestTimeout: 5 * time.Second,
|
||||||
}
|
}
|
||||||
@@ -58,12 +60,11 @@ var (
|
|||||||
type Tester struct {
|
type Tester struct {
|
||||||
Client *http.Client
|
Client *http.Client
|
||||||
configLoaded bool
|
configLoaded bool
|
||||||
t *testing.T
|
t testing.TB
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewTester will create a new testing client with an attached cookie jar
|
// NewTester will create a new testing client with an attached cookie jar
|
||||||
func NewTester(t *testing.T) *Tester {
|
func NewTester(t testing.TB) *Tester {
|
||||||
|
|
||||||
jar, err := cookiejar.New(nil)
|
jar, err := cookiejar.New(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failed to create cookiejar: %s", err)
|
t.Fatalf("failed to create cookiejar: %s", err)
|
||||||
@@ -94,7 +95,6 @@ func timeElapsed(start time.Time, name string) {
|
|||||||
// InitServer this will configure the server with a configurion of a specific
|
// InitServer this will configure the server with a configurion of a specific
|
||||||
// type. The configType must be either "json" or the adapter type.
|
// type. The configType must be either "json" or the adapter type.
|
||||||
func (tc *Tester) InitServer(rawConfig string, configType string) {
|
func (tc *Tester) InitServer(rawConfig string, configType string) {
|
||||||
|
|
||||||
if err := tc.initServer(rawConfig, configType); err != nil {
|
if err := tc.initServer(rawConfig, configType); err != nil {
|
||||||
tc.t.Logf("failed to load config: %s", err)
|
tc.t.Logf("failed to load config: %s", err)
|
||||||
tc.t.Fail()
|
tc.t.Fail()
|
||||||
@@ -108,7 +108,6 @@ func (tc *Tester) InitServer(rawConfig string, configType string) {
|
|||||||
// InitServer this will configure the server with a configurion of a specific
|
// InitServer this will configure the server with a configurion of a specific
|
||||||
// type. The configType must be either "json" or the adapter type.
|
// type. The configType must be either "json" or the adapter type.
|
||||||
func (tc *Tester) initServer(rawConfig string, configType string) error {
|
func (tc *Tester) initServer(rawConfig string, configType string) error {
|
||||||
|
|
||||||
if testing.Short() {
|
if testing.Short() {
|
||||||
tc.t.SkipNow()
|
tc.t.SkipNow()
|
||||||
return nil
|
return nil
|
||||||
@@ -122,7 +121,6 @@ func (tc *Tester) initServer(rawConfig string, configType string) error {
|
|||||||
|
|
||||||
tc.t.Cleanup(func() {
|
tc.t.Cleanup(func() {
|
||||||
if tc.t.Failed() && tc.configLoaded {
|
if tc.t.Failed() && tc.configLoaded {
|
||||||
|
|
||||||
res, err := http.Get(fmt.Sprintf("http://localhost:%d/config/", Default.AdminPort))
|
res, err := http.Get(fmt.Sprintf("http://localhost:%d/config/", Default.AdminPort))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Log("unable to read the current config")
|
tc.t.Log("unable to read the current config")
|
||||||
@@ -138,6 +136,20 @@ func (tc *Tester) initServer(rawConfig string, configType string) error {
|
|||||||
})
|
})
|
||||||
|
|
||||||
rawConfig = prependCaddyFilePath(rawConfig)
|
rawConfig = prependCaddyFilePath(rawConfig)
|
||||||
|
// normalize JSON config
|
||||||
|
if configType == "json" {
|
||||||
|
tc.t.Logf("Before: %s", rawConfig)
|
||||||
|
var conf any
|
||||||
|
if err := json.Unmarshal([]byte(rawConfig), &conf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c, err := json.Marshal(conf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rawConfig = string(c)
|
||||||
|
tc.t.Logf("After: %s", rawConfig)
|
||||||
|
}
|
||||||
client := &http.Client{
|
client := &http.Client{
|
||||||
Timeout: Default.LoadRequestTimeout,
|
Timeout: Default.LoadRequestTimeout,
|
||||||
}
|
}
|
||||||
@@ -231,11 +243,10 @@ const initConfig = `{
|
|||||||
|
|
||||||
// validateTestPrerequisites ensures the certificates are available in the
|
// validateTestPrerequisites ensures the certificates are available in the
|
||||||
// designated path and Caddy sub-process is running.
|
// designated path and Caddy sub-process is running.
|
||||||
func validateTestPrerequisites(t *testing.T) error {
|
func validateTestPrerequisites(t testing.TB) error {
|
||||||
|
|
||||||
// check certificates are found
|
// check certificates are found
|
||||||
for _, certName := range Default.Certifcates {
|
for _, certName := range Default.Certificates {
|
||||||
if _, err := os.Stat(getIntegrationDir() + certName); os.IsNotExist(err) {
|
if _, err := os.Stat(getIntegrationDir() + certName); errors.Is(err, fs.ErrNotExist) {
|
||||||
return fmt.Errorf("caddy integration test certificates (%s) not found", certName)
|
return fmt.Errorf("caddy integration test certificates (%s) not found", certName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,7 +295,6 @@ func isCaddyAdminRunning() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getIntegrationDir() string {
|
func getIntegrationDir() string {
|
||||||
|
|
||||||
_, filename, _, ok := runtime.Caller(1)
|
_, filename, _, ok := runtime.Caller(1)
|
||||||
if !ok {
|
if !ok {
|
||||||
panic("unable to determine the current file path")
|
panic("unable to determine the current file path")
|
||||||
@@ -304,7 +314,6 @@ func prependCaddyFilePath(rawConfig string) string {
|
|||||||
|
|
||||||
// CreateTestingTransport creates a testing transport that forces call dialing connections to happen locally
|
// CreateTestingTransport creates a testing transport that forces call dialing connections to happen locally
|
||||||
func CreateTestingTransport() *http.Transport {
|
func CreateTestingTransport() *http.Transport {
|
||||||
|
|
||||||
dialer := net.Dialer{
|
dialer := net.Dialer{
|
||||||
Timeout: 5 * time.Second,
|
Timeout: 5 * time.Second,
|
||||||
KeepAlive: 5 * time.Second,
|
KeepAlive: 5 * time.Second,
|
||||||
@@ -332,7 +341,6 @@ func CreateTestingTransport() *http.Transport {
|
|||||||
|
|
||||||
// AssertLoadError will load a config and expect an error
|
// AssertLoadError will load a config and expect an error
|
||||||
func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) {
|
func AssertLoadError(t *testing.T, rawConfig string, configType string, expectedError string) {
|
||||||
|
|
||||||
tc := NewTester(t)
|
tc := NewTester(t)
|
||||||
|
|
||||||
err := tc.initServer(rawConfig, configType)
|
err := tc.initServer(rawConfig, configType)
|
||||||
@@ -343,7 +351,6 @@ func AssertLoadError(t *testing.T, rawConfig string, configType string, expected
|
|||||||
|
|
||||||
// AssertRedirect makes a request and asserts the redirection happens
|
// AssertRedirect makes a request and asserts the redirection happens
|
||||||
func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, expectedStatusCode int) *http.Response {
|
func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, expectedStatusCode int) *http.Response {
|
||||||
|
|
||||||
redirectPolicyFunc := func(req *http.Request, via []*http.Request) error {
|
redirectPolicyFunc := func(req *http.Request, via []*http.Request) error {
|
||||||
return http.ErrUseLastResponse
|
return http.ErrUseLastResponse
|
||||||
}
|
}
|
||||||
@@ -380,8 +387,7 @@ func (tc *Tester) AssertRedirect(requestURI string, expectedToLocation string, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CompareAdapt adapts a config and then compares it against an expected result
|
// CompareAdapt adapts a config and then compares it against an expected result
|
||||||
func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string, expectedResponse string) bool {
|
func CompareAdapt(t testing.TB, filename, rawConfig string, adapterName string, expectedResponse string) bool {
|
||||||
|
|
||||||
cfgAdapter := caddyconfig.GetAdapter(adapterName)
|
cfgAdapter := caddyconfig.GetAdapter(adapterName)
|
||||||
if cfgAdapter == nil {
|
if cfgAdapter == nil {
|
||||||
t.Logf("unrecognized config adapter '%s'", adapterName)
|
t.Logf("unrecognized config adapter '%s'", adapterName)
|
||||||
@@ -440,7 +446,7 @@ func CompareAdapt(t *testing.T, filename, rawConfig string, adapterName string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AssertAdapt adapts a config and then tests it against an expected result
|
// AssertAdapt adapts a config and then tests it against an expected result
|
||||||
func AssertAdapt(t *testing.T, rawConfig string, adapterName string, expectedResponse string) {
|
func AssertAdapt(t testing.TB, rawConfig string, adapterName string, expectedResponse string) {
|
||||||
ok := CompareAdapt(t, "Caddyfile", rawConfig, adapterName, expectedResponse)
|
ok := CompareAdapt(t, "Caddyfile", rawConfig, adapterName, expectedResponse)
|
||||||
if !ok {
|
if !ok {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
@@ -449,7 +455,7 @@ func AssertAdapt(t *testing.T, rawConfig string, adapterName string, expectedRes
|
|||||||
|
|
||||||
// Generic request functions
|
// Generic request functions
|
||||||
|
|
||||||
func applyHeaders(t *testing.T, req *http.Request, requestHeaders []string) {
|
func applyHeaders(t testing.TB, req *http.Request, requestHeaders []string) {
|
||||||
requestContentType := ""
|
requestContentType := ""
|
||||||
for _, requestHeader := range requestHeaders {
|
for _, requestHeader := range requestHeaders {
|
||||||
arr := strings.SplitAfterN(requestHeader, ":", 2)
|
arr := strings.SplitAfterN(requestHeader, ":", 2)
|
||||||
@@ -469,14 +475,13 @@ func applyHeaders(t *testing.T, req *http.Request, requestHeaders []string) {
|
|||||||
|
|
||||||
// AssertResponseCode will execute the request and verify the status code, returns a response for additional assertions
|
// AssertResponseCode will execute the request and verify the status code, returns a response for additional assertions
|
||||||
func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) *http.Response {
|
func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int) *http.Response {
|
||||||
|
|
||||||
resp, err := tc.Client.Do(req)
|
resp, err := tc.Client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Fatalf("failed to call server %s", err)
|
tc.t.Fatalf("failed to call server %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if expectedStatusCode != resp.StatusCode {
|
if expectedStatusCode != resp.StatusCode {
|
||||||
tc.t.Errorf("requesting \"%s\" expected status code: %d but got %d", req.RequestURI, expectedStatusCode, resp.StatusCode)
|
tc.t.Errorf("requesting \"%s\" expected status code: %d but got %d", req.URL.RequestURI(), expectedStatusCode, resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
return resp
|
return resp
|
||||||
@@ -484,7 +489,6 @@ func (tc *Tester) AssertResponseCode(req *http.Request, expectedStatusCode int)
|
|||||||
|
|
||||||
// AssertResponse request a URI and assert the status code and the body contains a string
|
// AssertResponse request a URI and assert the status code and the body contains a string
|
||||||
func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
||||||
|
|
||||||
resp := tc.AssertResponseCode(req, expectedStatusCode)
|
resp := tc.AssertResponseCode(req, expectedStatusCode)
|
||||||
|
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
@@ -506,7 +510,6 @@ func (tc *Tester) AssertResponse(req *http.Request, expectedStatusCode int, expe
|
|||||||
|
|
||||||
// AssertGetResponse GET a URI and expect a statusCode and body text
|
// AssertGetResponse GET a URI and expect a statusCode and body text
|
||||||
func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
||||||
|
|
||||||
req, err := http.NewRequest("GET", requestURI, nil)
|
req, err := http.NewRequest("GET", requestURI, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Fatalf("unable to create request %s", err)
|
tc.t.Fatalf("unable to create request %s", err)
|
||||||
@@ -517,7 +520,6 @@ func (tc *Tester) AssertGetResponse(requestURI string, expectedStatusCode int, e
|
|||||||
|
|
||||||
// AssertDeleteResponse request a URI and expect a statusCode and body text
|
// AssertDeleteResponse request a URI and expect a statusCode and body text
|
||||||
func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
||||||
|
|
||||||
req, err := http.NewRequest("DELETE", requestURI, nil)
|
req, err := http.NewRequest("DELETE", requestURI, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Fatalf("unable to create request %s", err)
|
tc.t.Fatalf("unable to create request %s", err)
|
||||||
@@ -528,7 +530,6 @@ func (tc *Tester) AssertDeleteResponse(requestURI string, expectedStatusCode int
|
|||||||
|
|
||||||
// AssertPostResponseBody POST to a URI and assert the response code and body
|
// AssertPostResponseBody POST to a URI and assert the response code and body
|
||||||
func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
||||||
|
|
||||||
req, err := http.NewRequest("POST", requestURI, requestBody)
|
req, err := http.NewRequest("POST", requestURI, requestBody)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Errorf("failed to create request %s", err)
|
tc.t.Errorf("failed to create request %s", err)
|
||||||
@@ -542,7 +543,6 @@ func (tc *Tester) AssertPostResponseBody(requestURI string, requestHeaders []str
|
|||||||
|
|
||||||
// AssertPutResponseBody PUT to a URI and assert the response code and body
|
// AssertPutResponseBody PUT to a URI and assert the response code and body
|
||||||
func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
||||||
|
|
||||||
req, err := http.NewRequest("PUT", requestURI, requestBody)
|
req, err := http.NewRequest("PUT", requestURI, requestBody)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Errorf("failed to create request %s", err)
|
tc.t.Errorf("failed to create request %s", err)
|
||||||
@@ -556,7 +556,6 @@ func (tc *Tester) AssertPutResponseBody(requestURI string, requestHeaders []stri
|
|||||||
|
|
||||||
// AssertPatchResponseBody PATCH to a URI and assert the response code and body
|
// AssertPatchResponseBody PATCH to a URI and assert the response code and body
|
||||||
func (tc *Tester) AssertPatchResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
func (tc *Tester) AssertPatchResponseBody(requestURI string, requestHeaders []string, requestBody *bytes.Buffer, expectedStatusCode int, expectedBody string) (*http.Response, string) {
|
||||||
|
|
||||||
req, err := http.NewRequest("PATCH", requestURI, requestBody)
|
req, err := http.NewRequest("PATCH", requestURI, requestBody)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tc.t.Errorf("failed to create request %s", err)
|
tc.t.Errorf("failed to create request %s", err)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package caddytest
|
package caddytest
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@@ -31,3 +32,97 @@ func TestReplaceCertificatePaths(t *testing.T) {
|
|||||||
t.Error("expected redirect uri to be unchanged")
|
t.Error("expected redirect uri to be unchanged")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoadUnorderedJSON(t *testing.T) {
|
||||||
|
tester := NewTester(t)
|
||||||
|
tester.InitServer(`
|
||||||
|
{
|
||||||
|
"logging": {
|
||||||
|
"logs": {
|
||||||
|
"default": {
|
||||||
|
"level": "DEBUG",
|
||||||
|
"writer": {
|
||||||
|
"output": "stdout"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sStdOutLogs": {
|
||||||
|
"level": "DEBUG",
|
||||||
|
"writer": {
|
||||||
|
"output": "stdout"
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"http.*",
|
||||||
|
"admin.*"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"sFileLogs": {
|
||||||
|
"level": "DEBUG",
|
||||||
|
"writer": {
|
||||||
|
"output": "stdout"
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"http.*",
|
||||||
|
"admin.*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"admin": {
|
||||||
|
"listen": "localhost:2999"
|
||||||
|
},
|
||||||
|
"apps": {
|
||||||
|
"pki": {
|
||||||
|
"certificate_authorities" : {
|
||||||
|
"local" : {
|
||||||
|
"install_trust": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"http": {
|
||||||
|
"http_port": 9080,
|
||||||
|
"https_port": 9443,
|
||||||
|
"servers": {
|
||||||
|
"s_server": {
|
||||||
|
"listen": [
|
||||||
|
":9080"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"body": "Hello"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost",
|
||||||
|
"127.0.0.1"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"logs": {
|
||||||
|
"default_logger_name": "sStdOutLogs",
|
||||||
|
"logger_names": {
|
||||||
|
"localhost": "sStdOutLogs",
|
||||||
|
"127.0.0.1": "sFileLogs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`, "json")
|
||||||
|
req, err := http.NewRequest(http.MethodGet, "http://localhost:9080/", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fail()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tester.AssertResponseCode(req, 200)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
package integration
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2"
|
||||||
|
"github.com/caddyserver/caddy/v2/caddytest"
|
||||||
|
"github.com/mholt/acmez/v2"
|
||||||
|
"github.com/mholt/acmez/v2/acme"
|
||||||
|
smallstepacme "github.com/smallstep/certificates/acme"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
const acmeChallengePort = 9081
|
||||||
|
|
||||||
|
// Test the basic functionality of Caddy's ACME server
|
||||||
|
func TestACMEServerWithDefaults(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
logger, err := zap.NewDevelopment()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tester := caddytest.NewTester(t)
|
||||||
|
tester.InitServer(`
|
||||||
|
{
|
||||||
|
skip_install_trust
|
||||||
|
admin localhost:2999
|
||||||
|
http_port 9080
|
||||||
|
https_port 9443
|
||||||
|
local_certs
|
||||||
|
}
|
||||||
|
acme.localhost {
|
||||||
|
acme_server
|
||||||
|
}
|
||||||
|
`, "caddyfile")
|
||||||
|
|
||||||
|
client := acmez.Client{
|
||||||
|
Client: &acme.Client{
|
||||||
|
Directory: "https://acme.localhost:9443/acme/local/directory",
|
||||||
|
HTTPClient: tester.Client,
|
||||||
|
Logger: logger,
|
||||||
|
},
|
||||||
|
ChallengeSolvers: map[string]acmez.Solver{
|
||||||
|
acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating account key: %v", err)
|
||||||
|
}
|
||||||
|
account := acme.Account{
|
||||||
|
Contact: []string{"mailto:you@example.com"},
|
||||||
|
TermsOfServiceAgreed: true,
|
||||||
|
PrivateKey: accountPrivateKey,
|
||||||
|
}
|
||||||
|
account, err = client.NewAccount(ctx, account)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("new account: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every certificate needs a key.
|
||||||
|
certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating certificate key: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"})
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("obtaining certificate: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ACME servers should usually give you the entire certificate chain
|
||||||
|
// in PEM format, and sometimes even alternate chains! It's up to you
|
||||||
|
// which one(s) to store and use, but whatever you do, be sure to
|
||||||
|
// store the certificate and key somewhere safe and secure, i.e. don't
|
||||||
|
// lose them!
|
||||||
|
for _, cert := range certs {
|
||||||
|
t.Logf("Certificate %q:\n%s\n\n", cert.URL, cert.ChainPEM)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestACMEServerWithMismatchedChallenges(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
logger := caddy.Log().Named("acmez")
|
||||||
|
|
||||||
|
tester := caddytest.NewTester(t)
|
||||||
|
tester.InitServer(`
|
||||||
|
{
|
||||||
|
skip_install_trust
|
||||||
|
admin localhost:2999
|
||||||
|
http_port 9080
|
||||||
|
https_port 9443
|
||||||
|
local_certs
|
||||||
|
}
|
||||||
|
acme.localhost {
|
||||||
|
acme_server {
|
||||||
|
challenges tls-alpn-01
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`, "caddyfile")
|
||||||
|
|
||||||
|
client := acmez.Client{
|
||||||
|
Client: &acme.Client{
|
||||||
|
Directory: "https://acme.localhost:9443/acme/local/directory",
|
||||||
|
HTTPClient: tester.Client,
|
||||||
|
Logger: logger,
|
||||||
|
},
|
||||||
|
ChallengeSolvers: map[string]acmez.Solver{
|
||||||
|
acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating account key: %v", err)
|
||||||
|
}
|
||||||
|
account := acme.Account{
|
||||||
|
Contact: []string{"mailto:you@example.com"},
|
||||||
|
TermsOfServiceAgreed: true,
|
||||||
|
PrivateKey: accountPrivateKey,
|
||||||
|
}
|
||||||
|
account, err = client.NewAccount(ctx, account)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("new account: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every certificate needs a key.
|
||||||
|
certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating certificate key: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"})
|
||||||
|
if len(certs) > 0 {
|
||||||
|
t.Errorf("expected '0' certificates, but received '%d'", len(certs))
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
t.Error("expected errors, but received none")
|
||||||
|
}
|
||||||
|
const expectedErrMsg = "no solvers available for remaining challenges (configured=[http-01] offered=[tls-alpn-01] remaining=[tls-alpn-01])"
|
||||||
|
if !strings.Contains(err.Error(), expectedErrMsg) {
|
||||||
|
t.Errorf(`received error message does not match expectation: expected="%s" received="%s"`, expectedErrMsg, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// naiveHTTPSolver is a no-op acmez.Solver for example purposes only.
|
||||||
|
type naiveHTTPSolver struct {
|
||||||
|
srv *http.Server
|
||||||
|
logger *zap.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *naiveHTTPSolver) Present(ctx context.Context, challenge acme.Challenge) error {
|
||||||
|
smallstepacme.InsecurePortHTTP01 = acmeChallengePort
|
||||||
|
s.srv = &http.Server{
|
||||||
|
Addr: fmt.Sprintf(":%d", acmeChallengePort),
|
||||||
|
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
host, _, err := net.SplitHostPort(r.Host)
|
||||||
|
if err != nil {
|
||||||
|
host = r.Host
|
||||||
|
}
|
||||||
|
s.logger.Info("received request on challenge server", zap.String("path", r.URL.Path))
|
||||||
|
if r.Method == "GET" && r.URL.Path == challenge.HTTP01ResourcePath() && strings.EqualFold(host, challenge.Identifier.Value) {
|
||||||
|
w.Header().Add("Content-Type", "text/plain")
|
||||||
|
w.Write([]byte(challenge.KeyAuthorization))
|
||||||
|
r.Close = true
|
||||||
|
s.logger.Info("served key authentication",
|
||||||
|
zap.String("identifier", challenge.Identifier.Value),
|
||||||
|
zap.String("challenge", "http-01"),
|
||||||
|
zap.String("remote", r.RemoteAddr),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
l, err := net.Listen("tcp", fmt.Sprintf(":%d", acmeChallengePort))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.logger.Info("present challenge", zap.Any("challenge", challenge))
|
||||||
|
go s.srv.Serve(l)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s naiveHTTPSolver) CleanUp(ctx context.Context, challenge acme.Challenge) error {
|
||||||
|
smallstepacme.InsecurePortHTTP01 = 0
|
||||||
|
s.logger.Info("cleanup", zap.Any("challenge", challenge))
|
||||||
|
if s.srv != nil {
|
||||||
|
s.srv.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package integration
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/caddyserver/caddy/v2/caddytest"
|
||||||
|
"github.com/mholt/acmez/v2"
|
||||||
|
"github.com/mholt/acmez/v2/acme"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestACMEServerDirectory(t *testing.T) {
|
||||||
|
tester := caddytest.NewTester(t)
|
||||||
|
tester.InitServer(`
|
||||||
|
{
|
||||||
|
skip_install_trust
|
||||||
|
local_certs
|
||||||
|
admin localhost:2999
|
||||||
|
http_port 9080
|
||||||
|
https_port 9443
|
||||||
|
pki {
|
||||||
|
ca local {
|
||||||
|
name "Caddy Local Authority"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acme.localhost:9443 {
|
||||||
|
acme_server
|
||||||
|
}
|
||||||
|
`, "caddyfile")
|
||||||
|
tester.AssertGetResponse(
|
||||||
|
"https://acme.localhost:9443/acme/local/directory",
|
||||||
|
200,
|
||||||
|
`{"newNonce":"https://acme.localhost:9443/acme/local/new-nonce","newAccount":"https://acme.localhost:9443/acme/local/new-account","newOrder":"https://acme.localhost:9443/acme/local/new-order","revokeCert":"https://acme.localhost:9443/acme/local/revoke-cert","keyChange":"https://acme.localhost:9443/acme/local/key-change"}
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestACMEServerAllowPolicy(t *testing.T) {
|
||||||
|
tester := caddytest.NewTester(t)
|
||||||
|
tester.InitServer(`
|
||||||
|
{
|
||||||
|
skip_install_trust
|
||||||
|
local_certs
|
||||||
|
admin localhost:2999
|
||||||
|
http_port 9080
|
||||||
|
https_port 9443
|
||||||
|
pki {
|
||||||
|
ca local {
|
||||||
|
name "Caddy Local Authority"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acme.localhost {
|
||||||
|
acme_server {
|
||||||
|
challenges http-01
|
||||||
|
allow {
|
||||||
|
domains localhost
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`, "caddyfile")
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
logger, err := zap.NewDevelopment()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
client := acmez.Client{
|
||||||
|
Client: &acme.Client{
|
||||||
|
Directory: "https://acme.localhost:9443/acme/local/directory",
|
||||||
|
HTTPClient: tester.Client,
|
||||||
|
Logger: logger,
|
||||||
|
},
|
||||||
|
ChallengeSolvers: map[string]acmez.Solver{
|
||||||
|
acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating account key: %v", err)
|
||||||
|
}
|
||||||
|
account := acme.Account{
|
||||||
|
Contact: []string{"mailto:you@example.com"},
|
||||||
|
TermsOfServiceAgreed: true,
|
||||||
|
PrivateKey: accountPrivateKey,
|
||||||
|
}
|
||||||
|
account, err = client.NewAccount(ctx, account)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("new account: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every certificate needs a key.
|
||||||
|
certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating certificate key: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
{
|
||||||
|
certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"})
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("obtaining certificate for allowed domain: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ACME servers should usually give you the entire certificate chain
|
||||||
|
// in PEM format, and sometimes even alternate chains! It's up to you
|
||||||
|
// which one(s) to store and use, but whatever you do, be sure to
|
||||||
|
// store the certificate and key somewhere safe and secure, i.e. don't
|
||||||
|
// lose them!
|
||||||
|
for _, cert := range certs {
|
||||||
|
t.Logf("Certificate %q:\n%s\n\n", cert.URL, cert.ChainPEM)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{
|
||||||
|
_, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"not-matching.localhost"})
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("obtaining certificate for 'not-matching.localhost' domain")
|
||||||
|
} else if err != nil && !strings.Contains(err.Error(), "urn:ietf:params:acme:error:rejectedIdentifier") {
|
||||||
|
t.Logf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestACMEServerDenyPolicy(t *testing.T) {
|
||||||
|
tester := caddytest.NewTester(t)
|
||||||
|
tester.InitServer(`
|
||||||
|
{
|
||||||
|
skip_install_trust
|
||||||
|
local_certs
|
||||||
|
admin localhost:2999
|
||||||
|
http_port 9080
|
||||||
|
https_port 9443
|
||||||
|
pki {
|
||||||
|
ca local {
|
||||||
|
name "Caddy Local Authority"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acme.localhost {
|
||||||
|
acme_server {
|
||||||
|
deny {
|
||||||
|
domains deny.localhost
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`, "caddyfile")
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
logger, err := zap.NewDevelopment()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
client := acmez.Client{
|
||||||
|
Client: &acme.Client{
|
||||||
|
Directory: "https://acme.localhost:9443/acme/local/directory",
|
||||||
|
HTTPClient: tester.Client,
|
||||||
|
Logger: logger,
|
||||||
|
},
|
||||||
|
ChallengeSolvers: map[string]acmez.Solver{
|
||||||
|
acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating account key: %v", err)
|
||||||
|
}
|
||||||
|
account := acme.Account{
|
||||||
|
Contact: []string{"mailto:you@example.com"},
|
||||||
|
TermsOfServiceAgreed: true,
|
||||||
|
PrivateKey: accountPrivateKey,
|
||||||
|
}
|
||||||
|
account, err = client.NewAccount(ctx, account)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("new account: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every certificate needs a key.
|
||||||
|
certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("generating certificate key: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
{
|
||||||
|
_, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"deny.localhost"})
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("obtaining certificate for 'deny.localhost' domain")
|
||||||
|
} else if err != nil && !strings.Contains(err.Error(), "urn:ietf:params:acme:error:rejectedIdentifier") {
|
||||||
|
t.Logf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
{
|
||||||
|
pki {
|
||||||
|
ca custom-ca {
|
||||||
|
name "Custom CA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
acme.example.com {
|
||||||
|
acme_server {
|
||||||
|
ca custom-ca
|
||||||
|
challenges dns-01
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":443"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"acme.example.com"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"ca": "custom-ca",
|
||||||
|
"challenges": [
|
||||||
|
"dns-01"
|
||||||
|
],
|
||||||
|
"handler": "acme_server"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pki": {
|
||||||
|
"certificate_authorities": {
|
||||||
|
"custom-ca": {
|
||||||
|
"name": "Custom CA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
pki {
|
||||||
|
ca custom-ca {
|
||||||
|
name "Custom CA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
acme.example.com {
|
||||||
|
acme_server {
|
||||||
|
ca custom-ca
|
||||||
|
challenges
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":443"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"acme.example.com"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"ca": "custom-ca",
|
||||||
|
"handler": "acme_server"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pki": {
|
||||||
|
"certificate_authorities": {
|
||||||
|
"custom-ca": {
|
||||||
|
"name": "Custom CA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
{
|
||||||
|
pki {
|
||||||
|
ca custom-ca {
|
||||||
|
name "Custom CA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
acme.example.com {
|
||||||
|
acme_server {
|
||||||
|
ca custom-ca
|
||||||
|
challenges dns-01 http-01
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":443"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"acme.example.com"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"ca": "custom-ca",
|
||||||
|
"challenges": [
|
||||||
|
"dns-01",
|
||||||
|
"http-01"
|
||||||
|
],
|
||||||
|
"handler": "acme_server"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pki": {
|
||||||
|
"certificate_authorities": {
|
||||||
|
"custom-ca": {
|
||||||
|
"name": "Custom CA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
{
|
||||||
|
pki {
|
||||||
|
ca internal {
|
||||||
|
name "Internal"
|
||||||
|
root_cn "Internal Root Cert"
|
||||||
|
intermediate_cn "Internal Intermediate Cert"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
acme.example.com {
|
||||||
|
acme_server {
|
||||||
|
ca internal
|
||||||
|
sign_with_root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":443"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"acme.example.com"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"ca": "internal",
|
||||||
|
"handler": "acme_server",
|
||||||
|
"sign_with_root": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"pki": {
|
||||||
|
"certificate_authorities": {
|
||||||
|
"internal": {
|
||||||
|
"name": "Internal",
|
||||||
|
"root_common_name": "Internal Root Cert",
|
||||||
|
"intermediate_common_name": "Internal Intermediate Cert"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
{
|
||||||
|
auto_https prefer_wildcard
|
||||||
|
}
|
||||||
|
|
||||||
|
*.example.com {
|
||||||
|
tls {
|
||||||
|
dns mock
|
||||||
|
}
|
||||||
|
respond "fallback"
|
||||||
|
}
|
||||||
|
|
||||||
|
foo.example.com {
|
||||||
|
respond "foo"
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":443"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"foo.example.com"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "foo",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"*.example.com"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "fallback",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"automatic_https": {
|
||||||
|
"prefer_wildcard": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tls": {
|
||||||
|
"automation": {
|
||||||
|
"policies": [
|
||||||
|
{
|
||||||
|
"subjects": [
|
||||||
|
"*.example.com"
|
||||||
|
],
|
||||||
|
"issuers": [
|
||||||
|
{
|
||||||
|
"challenges": {
|
||||||
|
"dns": {
|
||||||
|
"provider": {
|
||||||
|
"name": "mock"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"module": "acme"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
{
|
||||||
|
auto_https disable_redirects
|
||||||
|
admin off
|
||||||
|
}
|
||||||
|
|
||||||
|
http://localhost {
|
||||||
|
bind fd/{env.CADDY_HTTP_FD} {
|
||||||
|
protocols h1
|
||||||
|
}
|
||||||
|
log
|
||||||
|
respond "Hello, HTTP!"
|
||||||
|
}
|
||||||
|
|
||||||
|
https://localhost {
|
||||||
|
bind fd/{env.CADDY_HTTPS_FD} {
|
||||||
|
protocols h1 h2
|
||||||
|
}
|
||||||
|
bind fdgram/{env.CADDY_HTTP3_FD} {
|
||||||
|
protocols h3
|
||||||
|
}
|
||||||
|
log
|
||||||
|
respond "Hello, HTTPS!"
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"admin": {
|
||||||
|
"disabled": true
|
||||||
|
},
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
"fd/{env.CADDY_HTTPS_FD}",
|
||||||
|
"fdgram/{env.CADDY_HTTP3_FD}"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Hello, HTTPS!",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true
|
||||||
|
},
|
||||||
|
"logs": {
|
||||||
|
"logger_names": {
|
||||||
|
"localhost": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"listen_protocols": [
|
||||||
|
[
|
||||||
|
"h1",
|
||||||
|
"h2"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"h3"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"srv1": {
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"srv2": {
|
||||||
|
"listen": [
|
||||||
|
"fd/{env.CADDY_HTTP_FD}"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Hello, HTTP!",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true,
|
||||||
|
"skip": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"logs": {
|
||||||
|
"logger_names": {
|
||||||
|
"localhost": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"listen_protocols": [
|
||||||
|
[
|
||||||
|
"h1"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
:8443 {
|
||||||
|
tls internal {
|
||||||
|
on_demand
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":8443"
|
||||||
|
],
|
||||||
|
"tls_connection_policies": [
|
||||||
|
{}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tls": {
|
||||||
|
"automation": {
|
||||||
|
"policies": [
|
||||||
|
{
|
||||||
|
"issuers": [
|
||||||
|
{
|
||||||
|
"module": "internal"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"on_demand": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+2
@@ -11,6 +11,7 @@ encode gzip zstd {
|
|||||||
header Content-Type application/xhtml+xml*
|
header Content-Type application/xhtml+xml*
|
||||||
header Content-Type application/atom+xml*
|
header Content-Type application/atom+xml*
|
||||||
header Content-Type application/rss+xml*
|
header Content-Type application/rss+xml*
|
||||||
|
header Content-Type application/wasm*
|
||||||
header Content-Type image/svg+xml*
|
header Content-Type image/svg+xml*
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,6 +48,7 @@ encode {
|
|||||||
"application/xhtml+xml*",
|
"application/xhtml+xml*",
|
||||||
"application/atom+xml*",
|
"application/atom+xml*",
|
||||||
"application/rss+xml*",
|
"application/rss+xml*",
|
||||||
|
"application/wasm*",
|
||||||
"image/svg+xml*"
|
"image/svg+xml*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
foo.localhost {
|
||||||
|
root * /srv
|
||||||
|
error /private* "Unauthorized" 410
|
||||||
|
error /fivehundred* "Internal Server Error" 500
|
||||||
|
|
||||||
|
handle_errors 5xx {
|
||||||
|
respond "Error In range [500 .. 599]"
|
||||||
|
}
|
||||||
|
handle_errors 410 {
|
||||||
|
respond "404 or 410 error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bar.localhost {
|
||||||
|
root * /srv
|
||||||
|
error /private* "Unauthorized" 410
|
||||||
|
error /fivehundred* "Internal Server Error" 500
|
||||||
|
|
||||||
|
handle_errors 5xx {
|
||||||
|
respond "Error In range [500 .. 599] from second site"
|
||||||
|
}
|
||||||
|
handle_errors 410 {
|
||||||
|
respond "404 or 410 error from second site"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":443"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"foo.localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "/srv"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Internal Server Error",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 500
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/fivehundred*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Unauthorized",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 410
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/private*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"bar.localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "/srv"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Internal Server Error",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 500
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/fivehundred*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Unauthorized",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 410
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/private*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": {
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"foo.localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "404 or 410 error",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} in [410]"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Error In range [500 .. 599]",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} \u003e= 500 \u0026\u0026 {http.error.status_code} \u003c= 599"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"bar.localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "404 or 410 error from second site",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} in [410]"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Error In range [500 .. 599] from second site",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} \u003e= 500 \u0026\u0026 {http.error.status_code} \u003c= 599"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
{
|
||||||
|
http_port 3010
|
||||||
|
}
|
||||||
|
localhost:3010 {
|
||||||
|
root * /srv
|
||||||
|
error /private* "Unauthorized" 410
|
||||||
|
error /hidden* "Not found" 404
|
||||||
|
|
||||||
|
handle_errors 4xx {
|
||||||
|
respond "Error in the [400 .. 499] range"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"http_port": 3010,
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":3010"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "/srv"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Unauthorized",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 410
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/private*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Not found",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/hidden*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": {
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Error in the [400 .. 499] range",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} \u003e= 400 \u0026\u0026 {http.error.status_code} \u003c= 499"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
{
|
||||||
|
http_port 2099
|
||||||
|
}
|
||||||
|
localhost:2099 {
|
||||||
|
root * /srv
|
||||||
|
error /private* "Unauthorized" 410
|
||||||
|
error /threehundred* "Moved Permanently" 301
|
||||||
|
error /internalerr* "Internal Server Error" 500
|
||||||
|
|
||||||
|
handle_errors 500 3xx {
|
||||||
|
respond "Error code is equal to 500 or in the [300..399] range"
|
||||||
|
}
|
||||||
|
handle_errors 4xx {
|
||||||
|
respond "Error in the [400 .. 499] range"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"http_port": 2099,
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":2099"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "/srv"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Moved Permanently",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 301
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/threehundred*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Internal Server Error",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 500
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/internalerr*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Unauthorized",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 410
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/private*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": {
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Error in the [400 .. 499] range",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} \u003e= 400 \u0026\u0026 {http.error.status_code} \u003c= 499"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Error code is equal to 500 or in the [300..399] range",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} \u003e= 300 \u0026\u0026 {http.error.status_code} \u003c= 399 || {http.error.status_code} in [500]"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
{
|
||||||
|
http_port 3010
|
||||||
|
}
|
||||||
|
localhost:3010 {
|
||||||
|
root * /srv
|
||||||
|
error /private* "Unauthorized" 410
|
||||||
|
error /hidden* "Not found" 404
|
||||||
|
|
||||||
|
handle_errors 404 410 {
|
||||||
|
respond "404 or 410 error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"http_port": 3010,
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":3010"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "/srv"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Unauthorized",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 410
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/private*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Not found",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/hidden*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": {
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "404 or 410 error",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} in [404, 410]"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
{
|
||||||
|
http_port 2099
|
||||||
|
}
|
||||||
|
localhost:2099 {
|
||||||
|
root * /srv
|
||||||
|
error /private* "Unauthorized" 410
|
||||||
|
error /hidden* "Not found" 404
|
||||||
|
error /internalerr* "Internal Server Error" 500
|
||||||
|
|
||||||
|
handle_errors {
|
||||||
|
respond "Fallback route: code outside the [400..499] range"
|
||||||
|
}
|
||||||
|
handle_errors 4xx {
|
||||||
|
respond "Error in the [400 .. 499] range"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"http_port": 2099,
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":2099"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "/srv"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Internal Server Error",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 500
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/internalerr*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Unauthorized",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 410
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/private*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"error": "Not found",
|
||||||
|
"handler": "error",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"path": [
|
||||||
|
"/hidden*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": {
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"localhost"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Error in the [400 .. 499] range",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": "{http.error.status_code} \u003e= 400 \u0026\u0026 {http.error.status_code} \u003c= 499"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"body": "Fallback route: code outside the [400..499] range",
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+50
-2
@@ -1,3 +1,7 @@
|
|||||||
|
(snippet) {
|
||||||
|
@g `{http.error.status_code} == 404`
|
||||||
|
}
|
||||||
|
|
||||||
example.com
|
example.com
|
||||||
|
|
||||||
@a expression {http.error.status_code} == 400
|
@a expression {http.error.status_code} == 400
|
||||||
@@ -14,6 +18,12 @@ abort @d
|
|||||||
|
|
||||||
@e expression `{http.error.status_code} == 404`
|
@e expression `{http.error.status_code} == 404`
|
||||||
abort @e
|
abort @e
|
||||||
|
|
||||||
|
@f `{http.error.status_code} == 404`
|
||||||
|
abort @f
|
||||||
|
|
||||||
|
import snippet
|
||||||
|
abort @g
|
||||||
----------
|
----------
|
||||||
{
|
{
|
||||||
"apps": {
|
"apps": {
|
||||||
@@ -84,7 +94,10 @@ abort @e
|
|||||||
],
|
],
|
||||||
"match": [
|
"match": [
|
||||||
{
|
{
|
||||||
"expression": "{http.error.status_code} == 403"
|
"expression": {
|
||||||
|
"expr": "{http.error.status_code} == 403",
|
||||||
|
"name": "d"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -97,7 +110,42 @@ abort @e
|
|||||||
],
|
],
|
||||||
"match": [
|
"match": [
|
||||||
{
|
{
|
||||||
"expression": "{http.error.status_code} == 404"
|
"expression": {
|
||||||
|
"expr": "{http.error.status_code} == 404",
|
||||||
|
"name": "e"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"abort": true,
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": {
|
||||||
|
"expr": "{http.error.status_code} == 404",
|
||||||
|
"name": "f"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"abort": true,
|
||||||
|
"handler": "static_response"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"expression": {
|
||||||
|
"expr": "{http.error.status_code} == 404",
|
||||||
|
"name": "g"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
:8080 {
|
||||||
|
root * ./
|
||||||
|
file_server {
|
||||||
|
etag_file_extensions .b3sum .sha256
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":8080"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars",
|
||||||
|
"root": "./"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"etag_file_extensions": [
|
||||||
|
".b3sum",
|
||||||
|
".sha256"
|
||||||
|
],
|
||||||
|
"handler": "file_server",
|
||||||
|
"hide": [
|
||||||
|
"./Caddyfile"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
:80
|
||||||
|
|
||||||
|
file_server {
|
||||||
|
browse {
|
||||||
|
sort size desc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":80"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"browse": {
|
||||||
|
"sort": [
|
||||||
|
"size",
|
||||||
|
"desc"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"handler": "file_server",
|
||||||
|
"hide": [
|
||||||
|
"./Caddyfile"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-7
@@ -17,8 +17,6 @@
|
|||||||
admin off
|
admin off
|
||||||
on_demand_tls {
|
on_demand_tls {
|
||||||
ask https://example.com
|
ask https://example.com
|
||||||
interval 30s
|
|
||||||
burst 20
|
|
||||||
}
|
}
|
||||||
local_certs
|
local_certs
|
||||||
key_type ed25519
|
key_type ed25519
|
||||||
@@ -69,11 +67,10 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"on_demand": {
|
"on_demand": {
|
||||||
"rate_limit": {
|
"permission": {
|
||||||
"interval": 30000000000,
|
"endpoint": "https://example.com",
|
||||||
"burst": 20
|
"module": "http"
|
||||||
},
|
}
|
||||||
"ask": "https://example.com"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"disable_ocsp_stapling": true
|
"disable_ocsp_stapling": true
|
||||||
+12
-7
@@ -17,8 +17,6 @@
|
|||||||
admin off
|
admin off
|
||||||
on_demand_tls {
|
on_demand_tls {
|
||||||
ask https://example.com
|
ask https://example.com
|
||||||
interval 30s
|
|
||||||
burst 20
|
|
||||||
}
|
}
|
||||||
storage_clean_interval 7d
|
storage_clean_interval 7d
|
||||||
renew_interval 1d
|
renew_interval 1d
|
||||||
@@ -63,6 +61,14 @@
|
|||||||
"issuers": [
|
"issuers": [
|
||||||
{
|
{
|
||||||
"ca": "https://example.com",
|
"ca": "https://example.com",
|
||||||
|
"challenges": {
|
||||||
|
"http": {
|
||||||
|
"alternate_port": 8080
|
||||||
|
},
|
||||||
|
"tls-alpn": {
|
||||||
|
"alternate_port": 8443
|
||||||
|
}
|
||||||
|
},
|
||||||
"email": "test@example.com",
|
"email": "test@example.com",
|
||||||
"external_account": {
|
"external_account": {
|
||||||
"key_id": "4K2scIVbBpNd-78scadB2g",
|
"key_id": "4K2scIVbBpNd-78scadB2g",
|
||||||
@@ -78,11 +84,10 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"on_demand": {
|
"on_demand": {
|
||||||
"rate_limit": {
|
"permission": {
|
||||||
"interval": 30000000000,
|
"endpoint": "https://example.com",
|
||||||
"burst": 20
|
"module": "http"
|
||||||
},
|
}
|
||||||
"ask": "https://example.com"
|
|
||||||
},
|
},
|
||||||
"ocsp_interval": 172800000000000,
|
"ocsp_interval": 172800000000000,
|
||||||
"renew_interval": 86400000000000,
|
"renew_interval": 86400000000000,
|
||||||
+4
-7
@@ -16,8 +16,6 @@
|
|||||||
}
|
}
|
||||||
on_demand_tls {
|
on_demand_tls {
|
||||||
ask https://example.com
|
ask https://example.com
|
||||||
interval 30s
|
|
||||||
burst 20
|
|
||||||
}
|
}
|
||||||
local_certs
|
local_certs
|
||||||
key_type ed25519
|
key_type ed25519
|
||||||
@@ -71,11 +69,10 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"on_demand": {
|
"on_demand": {
|
||||||
"rate_limit": {
|
"permission": {
|
||||||
"interval": 30000000000,
|
"endpoint": "https://example.com",
|
||||||
"burst": 20
|
"module": "http"
|
||||||
},
|
}
|
||||||
"ask": "https://example.com"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
-6
@@ -40,12 +40,6 @@ example.com
|
|||||||
"preferred_chains": {
|
"preferred_chains": {
|
||||||
"smallest": true
|
"smallest": true
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"module": "zerossl",
|
|
||||||
"preferred_chains": {
|
|
||||||
"smallest": true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+1
@@ -6,6 +6,7 @@ example.com {
|
|||||||
</html>
|
</html>
|
||||||
EOF 200
|
EOF 200
|
||||||
}
|
}
|
||||||
|
|
||||||
----------
|
----------
|
||||||
{
|
{
|
||||||
"apps": {
|
"apps": {
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
http://handle {
|
||||||
|
file_server
|
||||||
|
}
|
||||||
|
----------
|
||||||
|
{
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"servers": {
|
||||||
|
"srv0": {
|
||||||
|
"listen": [
|
||||||
|
":80"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"handle"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "file_server",
|
||||||
|
"hide": [
|
||||||
|
"./Caddyfile"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-2
@@ -72,8 +72,12 @@ b.example.com {
|
|||||||
],
|
],
|
||||||
"logs": {
|
"logs": {
|
||||||
"logger_names": {
|
"logger_names": {
|
||||||
"a.example.com": "log0",
|
"a.example.com": [
|
||||||
"b.example.com": "log1"
|
"log0"
|
||||||
|
],
|
||||||
|
"b.example.com": [
|
||||||
|
"log1"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user