Compare commits

...

50 Commits

Author SHA1 Message Date
bytetigers
a067fb1760
chore: fix struct name in comment (#7114)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m24s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m26s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m26s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m18s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m54s
Lint / govulncheck (push) Successful in 1m14s
Lint / dependency-review (push) Failing after 25s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
OpenSSF Scorecard supply-chain security / Scorecard analysis (push) Has started running
Signed-off-by: bytetigers <bytetiger@icloud.com>
2025-07-08 08:00:58 +00:00
Francis Lavoie
77dd12cc78
httpcaddyfile: Validates TLS DNS challenge options (#7099)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m9s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m28s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m22s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m20s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m15s
Lint / govulncheck (push) Successful in 1m34s
Lint / dependency-review (push) Failing after 50s
OpenSSF Scorecard supply-chain security / Scorecard analysis (push) Failing after 1m37s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
* httpcaddyfile: Validates TLS DNS challenge options

Adds validation to the TLS Caddyfile adapter to ensure that when DNS challenge options (such as propagation_delay or dns_ttl) are specified, a DNS provider is also configured.

Adds new integration tests to verify this validation logic, and implements a new mechanism for adapt tests to assert a config adapt error.

* Add some more AI-generated tests asserting config errors

* Parallel doesn't work here, we use global variables

* Windows fix
2025-06-30 23:58:16 +00:00
mountdisk
c712cfcd76
docs: fix some minor issues in the comments (#7101) 2025-06-30 06:50:00 +00:00
gopherorg
33c88bd2bb
refactor: replace HasPrefix+TrimPrefix with CutPrefix (#7095)
Signed-off-by: gopherorg <gopherworld@icloud.com>
2025-06-27 22:04:09 +03:00
Marten Seemann
11c6daecd7
go.mod: update quic-go to v0.53.0 (#7094) 2025-06-26 10:13:08 -06:00
filipRatajczak
3b4d966fba
fileserver: Add sort buttons in grid mode (#7089)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m30s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m22s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m21s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m13s
Lint / govulncheck (push) Successful in 1m36s
Lint / dependency-review (push) Failing after 53s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
OpenSSF Scorecard supply-chain security / Scorecard analysis (push) Has started running
* [ADD] sort buttons in grid mode

* [CHANGE] replace spaces with tabs
2025-06-23 13:26:45 -06:00
曹家巧
070d454c0d
Use the built-in max/min to simplify the code (#7081)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m53s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m35s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m29s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m28s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m28s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m21s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m57s
Lint / govulncheck (push) Successful in 1m31s
Lint / dependency-review (push) Failing after 41s
OpenSSF Scorecard supply-chain security / Scorecard analysis (push) Failing after 2s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Signed-off-by: xiaoxiangirl <caojiaqiao@outlook.com>
2025-06-19 16:39:48 -06:00
Mohammed Al Sahaf
2f0fc62b34
chore: apply security best practices for CI (#7066)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 3m9s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m37s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m32s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m42s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m47s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m44s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m46s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m32s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m27s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m26s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m30s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m18s
Lint / govulncheck (push) Successful in 1m24s
Lint / dependency-review (push) Failing after 1m1s
OpenSSF Scorecard supply-chain security / Scorecard analysis (push) Failing after 2s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
* chore: apply security best practices for CI

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* remove redundant codeql job

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* run scorecard flow on PRs

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

---------

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-06-16 20:14:09 +00:00
WeidiDeng
3d0b4fac5a
core: Clean up new config if it failed to run (#7068) 2025-06-16 13:15:41 -06:00
Mohammed Al Sahaf
1a0f168b6e
ci: add {base,head}-ref to dep review check (#7064)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m28s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m22s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m22s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m17s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m52s
Lint / govulncheck (push) Successful in 1m19s
Lint / dependency-review (push) Failing after 49s
OpenSSF Scorecard supply-chain security / Scorecard analysis (push) Failing after 2s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-06-13 08:13:17 +03:00
Mohammed Al Sahaf
7a33f481f1
ci: add dep review, OSSF scorecard actions (#7063)
* ci: add dep review action

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* sprinkle permissions on Actions jobs

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* README: add OpenSSF best practices badge

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* add draft OpenSSF Scorecard workflow

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

---------

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-06-12 23:40:51 +00:00
Herman Slatman
e633d013f6
cmd: fix Commands function not returning all registered commands (#7059) 2025-06-12 17:17:51 -06:00
Matt Holt
fe26751491
Update SECURITY.md
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m35s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m39s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m13s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m49s
Lint / govulncheck (push) Successful in 1m16s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
2025-06-12 09:38:48 -06:00
dependabot[bot]
4b01d77b81
build(deps): bump github.com/cloudflare/circl from 1.6.0 to 1.6.1 (#7058)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m46s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m27s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m29s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m16s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m47s
Lint / govulncheck (push) Successful in 1m16s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Bumps [github.com/cloudflare/circl](https://github.com/cloudflare/circl) from 1.6.0 to 1.6.1.
- [Release notes](https://github.com/cloudflare/circl/releases)
- [Commits](https://github.com/cloudflare/circl/compare/v1.6.0...v1.6.1)

---
updated-dependencies:
- dependency-name: github.com/cloudflare/circl
  dependency-version: 1.6.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-12 11:44:26 +03:00
Hina🐣 | Developer
0f209f62eb
httpcaddyfile: reject blocks in log_skip directive (#7056)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m26s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m50s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m14s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m48s
Lint / govulncheck (push) Successful in 1m16s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
2025-06-09 21:56:21 -06:00
Mohammed Al Sahaf
1481c0411a
caddytls: wire up client_auth leaf verifier Caddyfile (#6772)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m41s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 2m7s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m16s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m48s
Lint / govulncheck (push) Successful in 1m18s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
* client_auth: wire up leaf verifier Caddyfile

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* review feedback + tests

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

---------

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-06-09 08:18:36 -06:00
Youness Farini
092913a7a5
httpcaddyfile: Prevent error handler from overriding sub-handler matchers (#6999)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m52s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m33s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m15s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m49s
Lint / govulncheck (push) Successful in 1m16s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Fixes: #6957
2025-06-06 11:46:39 -06:00
Laurin
7099892958
core: Check for nil event origin (#7047)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m0s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m15s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m50s
Lint / govulncheck (push) Successful in 1m19s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
* fix: crash - null check on event origin

* chore: use accessor instead of property
2025-06-05 19:10:08 +00:00
dependabot[bot]
45c9341deb
build(deps): bump golangci/golangci-lint-action from 6 to 8 (#7044)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m44s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m30s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m14s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m9s
Lint / govulncheck (push) Successful in 1m18s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Bumps [golangci/golangci-lint-action](https://github.com/golangci/golangci-lint-action) from 6 to 8.
- [Release notes](https://github.com/golangci/golangci-lint-action/releases)
- [Commits](https://github.com/golangci/golangci-lint-action/compare/v6...v8)

---
updated-dependencies:
- dependency-name: golangci/golangci-lint-action
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-03 02:33:40 +03:00
Mohammed Al Sahaf
e039a5bb5c
chore: upgrade .golangci.yml and workflow to v2 (#6924)
* chore: upgrade .golangci.yml and workflow to v2

run `golangci-lint fmt`

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* run `golangci-lint run --fix`

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* more lint fixes

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* bring back comments to .golangci.yml

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* appease the linter some more

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* oops

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* use embedded structs

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* use embedded structs where they were used before

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* disable rule  `-QF1006`

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* missed a spot

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

---------

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-06-03 02:24:32 +03:00
tongjicoder
5b2eb66418
Use slices.Contains to simplify code (#7039)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m25s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m27s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m24s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m25s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m23s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m17s
Lint / govulncheck (push) Successful in 1m43s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Signed-off-by: tongjicoder <tongjicoder@icloud.com>
2025-05-31 12:03:06 -06:00
eveneast
a76d005a94
Use maps.Copy for simpler map handling (#7009)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m19s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m45s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m14s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m48s
Lint / govulncheck (push) Successful in 1m16s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Signed-off-by: eveneast <qcqs@foxmail.com>
2025-05-13 15:16:47 -06:00
WeidiDeng
8524386737
caddyhttp: Compare paths w/o wildcard if prefixes differ (#7015)
* fix route sort by comparing paths without wildcard if they don't share the same prefix

* sort lexically if paths have the same length
2025-05-13 13:17:52 -06:00
Jimmy Lipham
94147caf31
fileserver: map invalid path errors to fs.ErrInvalid, and return 400 for any invalid path errors. (close #7008) (#7017)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m18s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m36s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m22s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m15s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m46s
Lint / govulncheck (push) Successful in 1m15s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
2025-05-13 07:43:27 -06:00
WeidiDeng
716d72e475
intercept: implement Unwrap for interceptedResponseHandler (#7016)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m20s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m50s
Lint / govulncheck (push) Successful in 1m16s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
2025-05-12 12:15:34 -06:00
Mohammed Al Sahaf
44d078b670
acme_server: fix policy parsing in caddyfile (#7006)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m55s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m15s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m2s
Lint / govulncheck (push) Successful in 1m32s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-05-08 11:54:07 -06:00
Jimmy Lipham
051e73aefc
core: Replace admin server later in provisionContext (#7004) 2025-05-08 11:52:55 -06:00
Mohammed Al Sahaf
9f7148392a
log: default logger should respect {in,ex}clude (#6995)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m48s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m36s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m15s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m16s
Lint / lint (ubuntu-latest, linux) (push) Successful in 1m49s
Lint / govulncheck (push) Successful in 1m16s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
* log: default logger should respect `{in,ex}clude`

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

* add tests

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>

---------

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-05-06 22:06:09 +00:00
Jimmy Lipham
320c57291d
admin: Make sure that any admin routers are provisioned when local/re… (#6997)
* admin: Make sure that any admin routers are provisioned when local/remote admin servers are replaced at runtime.

* admin: check for provisioning errors during admin server replacements
2025-05-06 15:28:38 -06:00
WeidiDeng
aa3d20be3e
reverseproxy: Use DialTLSContext if ServerName has placeholder (#6955)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m56s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m11s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m11s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m11s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m11s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m13s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m9s
Lint / govulncheck (push) Successful in 1m30s
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
2025-04-28 09:14:09 -06:00
Steffen Busch
54d03ced48
fileserver: Add support for .avif image format (#6988) 2025-04-28 08:32:59 -06:00
Indra Gunawan
89ed5f44de
fix: Remove nil arg from zapslog.NewHandler call (#6984) 2025-04-28 08:31:10 -06:00
Matthew Holt
105eee671c caddytls: Set local_ip, not remote_ip (#6952)
Follow-up on 35c8c2d92d26208642cea0d1549c77a00124e154 where I was a dum-dum
2025-04-21 18:32:51 -06:00
Mohammed Al Sahaf
737936c06b
reverseproxy: reference correct field name in LoadModule (#6978)
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2025-04-21 08:43:27 -06:00
Marten Seemann
a6d488a15b
go.mod: update quic-go to v0.51.0 (#6972) 2025-04-20 07:39:00 -06:00
Matthew Holt
fb22a26b1a
caddytls: Allow missing ECH meta file 2025-04-18 12:20:21 -06:00
Matt Holt
1bfa111552
caddytls: Prefer managed wildcard certs over individual subdomain certs (#6959)
* caddytls: Prefer managed wildcard certs over individual subdomain certs

* Repurpose force_automate as no_wildcard

* Fix a couple bugs

* Restore force_automate and use automate loader as wildcard override
2025-04-18 11:44:23 -06:00
Matthew Holt
35c8c2d92d
caddytls: Add remote_ip to HTTP cert manager (close #6952) 2025-04-17 16:43:06 -06:00
dependabot[bot]
0b2802faa4
build(deps): bump golang.org/x/net from 0.37.0 to 0.38.0 (#6960)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.37.0 to 0.38.0.
- [Commits](https://github.com/golang/net/compare/v0.37.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.38.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-16 23:34:35 +00:00
Steffen Busch
5be77d07ab
caddyauth: Set authentication provider error in placeholder (#6932)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 14m36s
Cross-Build / build (~1.24.1, 1.24, aix) (push) Failing after 11m6s
Tests / goreleaser-check (push) Failing after 11m28s
Tests / test (s390x on IBM Z) (push) Failing after 14m29s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Failing after 12m46s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Failing after 13m31s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Failing after 14m3s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Failing after 15m15s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Failing after 16m19s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Failing after 10m2s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Failing after 12m22s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Failing after 13m50s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Failing after 14m12s
Lint / lint (ubuntu-latest, linux) (push) Failing after 14m26s
Lint / govulncheck (push) Failing after 14m14s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
* caddyauth: Set authentication provider error in placeholder for handle_errors directive

* caddyauth: Simplify error placeholder setting for authentication provider
2025-04-15 22:32:08 +00:00
Matthew Holt
137711ae3e
go.mod: Upgrade acmez and certmagic 2025-04-15 15:08:12 -06:00
Matthew Holt
f297bc0a04
admin: Remove host checking for UDS (close #6832)
The consensus is that host enforcement on unix sockets is ineffective, frustrating, and confusing. (Unix sockets have their own OS-level permissions system.)
2025-04-15 14:20:22 -06:00
Jesper Brix Rosenkilde
6c38ae7381
reverseproxy: Add valid Upstream to DialInfo in active health checks (#6949)
Currently if we extract the DialInfo from a Request Context during an active health check, then the Upstream in the DialInfo is nil.

This PR attempts to set the Upstream to a sensible value, based on wether or not the Upstream has been overriden in the active health check's config.
2025-04-15 08:44:53 -06:00
cui fliter
def9db1f16
Fix the incorrect parameter order (#6951)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Waiting to run
Lint / lint (macos-14, mac) (push) Waiting to run
Lint / lint (windows-latest, windows) (push) Waiting to run
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m53s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m16s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m14s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m13s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m12s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m14s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m7s
Lint / govulncheck (push) Successful in 1m27s
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Signed-off-by: cuishuang <imcusg@gmail.com>
2025-04-12 21:19:32 -06:00
riyueguang
ce926b87ed
chore: fix comment (#6950)
Signed-off-by: riyueguang <rustruby@outlook.com>
2025-04-12 04:24:17 +00:00
Matthew Holt
b06a9496d1
caddyhttp: Document side effect of HTTP/3 early data (close #6936) 2025-04-08 13:59:02 -06:00
Matthew Holt
9becf61a9f
go.mod: Upgrade to libdns 1.0 beta APIs (requires upgraded DNS providers)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m27s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m17s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m23s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m18s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m19s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m26s
Lint / govulncheck (push) Successful in 1m38s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
This is the only way we can properly, reliably support ECH.
2025-04-07 12:43:11 -06:00
Matt Holt
5a6b2f8d1d
events: Refactor; move Event into core, so core can emit events (#6930)
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m46s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 2m49s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 2m10s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m40s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m50s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m49s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 2m4s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 2m7s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 2m2s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 3m30s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 2m56s
Lint / lint (ubuntu-latest, linux) (push) Failing after 1m17s
Lint / govulncheck (push) Successful in 2m18s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
* events: Refactor; move Event into core, so core can emit events

Requires some slight trickery to invert dependencies. We can't have the caddy package import the caddyevents package, because caddyevents imports caddy. Interface to the rescue!

Also add two new events, experimentally: started, and stopping. At the request of a sponsor.

Also rename "Filesystems" to "FileSystems" to match Go convention (unrelated to events, was just bugging me when I noticed it).

* Coupla bug fixes

* lol whoops
2025-03-29 08:15:43 -06:00
Matthew Holt
ea77a9ab67
caddytls: Temporarily treat "" and "@" as equivalent for DNS publication
Some checks failed
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 1m41s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m33s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m29s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m29s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Failing after 13m24s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m45s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m22s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m19s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m21s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m32s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m0s
Lint / govulncheck (push) Successful in 1m12s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Lint / lint (macos-14, mac) (push) Has been cancelled
Lint / lint (windows-latest, windows) (push) Has been cancelled
Fixes https://github.com/caddyserver/caddy/issues/6895#issuecomment-2750111096
2025-03-25 16:24:16 -06:00
Matthew Holt
7672b7848f
go.mod: Upgrade CertMagic
Some checks failed
Lint / lint (macos-14, mac) (push) Waiting to run
Lint / lint (windows-latest, windows) (push) Waiting to run
Tests / test (./cmd/caddy/caddy, ~1.24.1, ubuntu-latest, 0, 1.24, linux) (push) Failing after 2m5s
Tests / test (s390x on IBM Z) (push) Has been skipped
Tests / goreleaser-check (push) Has been skipped
Cross-Build / build (~1.24.1, 1.24, aix) (push) Successful in 1m37s
Cross-Build / build (~1.24.1, 1.24, darwin) (push) Successful in 1m31s
Cross-Build / build (~1.24.1, 1.24, dragonfly) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, freebsd) (push) Successful in 1m29s
Cross-Build / build (~1.24.1, 1.24, illumos) (push) Successful in 1m33s
Cross-Build / build (~1.24.1, 1.24, linux) (push) Successful in 1m20s
Cross-Build / build (~1.24.1, 1.24, netbsd) (push) Successful in 1m32s
Cross-Build / build (~1.24.1, 1.24, openbsd) (push) Successful in 1m24s
Cross-Build / build (~1.24.1, 1.24, solaris) (push) Successful in 1m37s
Cross-Build / build (~1.24.1, 1.24, windows) (push) Successful in 1m35s
Lint / lint (ubuntu-latest, linux) (push) Successful in 2m30s
Lint / govulncheck (push) Successful in 1m29s
Tests / test (./cmd/caddy/caddy, ~1.24.1, macos-14, 0, 1.24, mac) (push) Has been cancelled
Tests / test (./cmd/caddy/caddy.exe, ~1.24.1, windows-latest, True, 1.24, windows) (push) Has been cancelled
Hotfix for wildcard certs (regression in beta 3)
2025-03-24 20:51:05 -06:00
128 changed files with 2877 additions and 1523 deletions

4
.github/SECURITY.md vendored
View File

@ -48,9 +48,9 @@ We consider publicly-registered domain names to be public information. This nece
It will speed things up if you suggest a working patch, such as a code diff, and explain why and how it works. Reports that are not actionable, do not contain enough information, are too pushy/demanding, or are not able to convince us that it is a viable and practical attack on the web server itself may be deferred to a later time or possibly ignored, depending on available resources. Priority will be given to credible, responsible reports that are constructive, specific, and actionable. (We get a lot of invalid reports.) Thank you for understanding. It will speed things up if you suggest a working patch, such as a code diff, and explain why and how it works. Reports that are not actionable, do not contain enough information, are too pushy/demanding, or are not able to convince us that it is a viable and practical attack on the web server itself may be deferred to a later time or possibly ignored, depending on available resources. Priority will be given to credible, responsible reports that are constructive, specific, and actionable. (We get a lot of invalid reports.) Thank you for understanding.
When you are ready, please email Matt Holt (the author) directly: matt at dyanim dot com. When you are ready, please submit a [new private vulnerability report](https://github.com/caddyserver/caddy/security/advisories/new).
Please don't encrypt the email body. It only makes the process more complicated. Please don't encrypt the message. It only makes the process more complicated.
Please also understand that due to our nature as an open source project, we do not have a budget to award security bounties. We can only thank you. Please also understand that due to our nature as an open source project, we do not have a budget to award security bounties. We can only thank you.

View File

@ -5,3 +5,8 @@ updates:
directory: "/" directory: "/"
schedule: schedule:
interval: "monthly" interval: "monthly"
- package-ecosystem: gomod
directory: /
schedule:
interval: weekly

View File

@ -16,6 +16,9 @@ env:
# https://github.com/actions/setup-go/issues/491 # https://github.com/actions/setup-go/issues/491
GOTOOLCHAIN: local GOTOOLCHAIN: local
permissions:
contents: read
jobs: jobs:
test: test:
strategy: strategy:
@ -55,13 +58,21 @@ jobs:
SUCCESS: 'True' SUCCESS: 'True'
runs-on: ${{ matrix.OS_LABEL }} runs-on: ${{ matrix.OS_LABEL }}
permissions:
contents: read
pull-requests: read
actions: write # to allow uploading artifacts and cache
steps: steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with: with:
go-version: ${{ matrix.GO_SEMVER }} go-version: ${{ matrix.GO_SEMVER }}
check-latest: true check-latest: true
@ -108,7 +119,7 @@ jobs:
./caddy stop ./caddy stop
- name: Publish Build Artifact - name: Publish Build Artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
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 }}
@ -142,12 +153,21 @@ jobs:
s390x-test: s390x-test:
name: test (s390x on IBM Z) name: test (s390x on IBM Z)
permissions:
contents: read
pull-requests: read
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.event.pull_request.head.repo.full_name == 'caddyserver/caddy' && github.actor != 'dependabot[bot]' if: github.event.pull_request.head.repo.full_name == 'caddyserver/caddy' && github.actor != 'dependabot[bot]'
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: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
allowed-endpoints: ci-s390x.caddyserver.com:22
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Run Tests - name: Run Tests
run: | run: |
set +e set +e
@ -194,17 +214,25 @@ jobs:
goreleaser-check: goreleaser-check:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
if: github.event.pull_request.head.repo.full_name == 'caddyserver/caddy' && github.actor != 'dependabot[bot]' if: github.event.pull_request.head.repo.full_name == 'caddyserver/caddy' && github.actor != 'dependabot[bot]'
steps: steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: goreleaser/goreleaser-action@v6 - uses: goreleaser/goreleaser-action@9c156ee8a17a598857849441385a2041ef570552 # v6.3.0
with: with:
version: latest version: latest
args: check args: check
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with: with:
go-version: "~1.24" go-version: "~1.24"
check-latest: true check-latest: true
@ -212,7 +240,7 @@ jobs:
run: | run: |
go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
xcaddy version xcaddy version
- uses: goreleaser/goreleaser-action@v6 - uses: goreleaser/goreleaser-action@9c156ee8a17a598857849441385a2041ef570552 # v6.3.0
with: with:
version: latest version: latest
args: build --single-target --snapshot args: build --single-target --snapshot

View File

@ -14,6 +14,9 @@ env:
# https://github.com/actions/setup-go/issues/491 # https://github.com/actions/setup-go/issues/491
GOTOOLCHAIN: local GOTOOLCHAIN: local
permissions:
contents: read
jobs: jobs:
build: build:
strategy: strategy:
@ -40,13 +43,21 @@ jobs:
GO_SEMVER: '~1.24.1' GO_SEMVER: '~1.24.1'
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
continue-on-error: true continue-on-error: true
steps: steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with: with:
go-version: ${{ matrix.GO_SEMVER }} go-version: ${{ matrix.GO_SEMVER }}
check-latest: true check-latest: true

View File

@ -44,14 +44,19 @@ jobs:
runs-on: ${{ matrix.OS_LABEL }} runs-on: ${{ matrix.OS_LABEL }}
steps: steps:
- uses: actions/checkout@v4 - name: Harden the runner (Audit all outbound calls)
- uses: actions/setup-go@v5 uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with: with:
go-version: '~1.24' go-version: '~1.24'
check-latest: true check-latest: true
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v6 uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # v8.0.0
with: with:
version: latest version: latest
@ -62,10 +67,39 @@ jobs:
# only-new-issues: true # only-new-issues: true
govulncheck: govulncheck:
permissions:
contents: read
pull-requests: read
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: govulncheck - name: govulncheck
uses: golang/govulncheck-action@v1 uses: golang/govulncheck-action@b625fbe08f3bccbe446d94fbf87fcc875a4f50ee # v1.0.4
with: with:
go-version-input: '~1.24.1' go-version-input: '~1.24.1'
check-latest: true check-latest: true
dependency-review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: 'Checkout Repository'
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: 'Dependency Review'
uses: actions/dependency-review-action@da24556b548a50705dd671f47852072ea4c105d9 # v4.7.1
with:
comment-summary-in-pr: on-failure
# https://github.com/actions/dependency-review-action/issues/430#issuecomment-1468975566
base-ref: ${{ github.event.pull_request.base.sha || 'master' }}
head-ref: ${{ github.event.pull_request.head.sha || github.ref }}

View File

@ -9,6 +9,9 @@ env:
# https://github.com/actions/setup-go/issues/491 # https://github.com/actions/setup-go/issues/491
GOTOOLCHAIN: local GOTOOLCHAIN: local
permissions:
contents: read
jobs: jobs:
release: release:
name: Release name: Release
@ -35,19 +38,24 @@ jobs:
contents: write contents: write
steps: steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Install Go - name: Install Go
uses: actions/setup-go@v5 uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
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@v4 runs this line: # tl;dr: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 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
@ -101,11 +109,11 @@ jobs:
git verify-tag "${{ steps.vars.outputs.version_tag }}" || exit 1 git verify-tag "${{ steps.vars.outputs.version_tag }}" || exit 1
- name: Install Cosign - name: Install Cosign
uses: sigstore/cosign-installer@main uses: sigstore/cosign-installer@e9a05e6d32d7ed22b5656cd874ef31af58d05bfa # main
- name: Cosign version - name: Cosign version
run: cosign version run: cosign version
- name: Install Syft - name: Install Syft
uses: anchore/sbom-action/download-syft@main uses: anchore/sbom-action/download-syft@9246b90769f852b3a8921f330c59e0b3f439d6e9 # main
- name: Syft version - name: Syft version
run: syft version run: syft version
- name: Install xcaddy - name: Install xcaddy
@ -114,7 +122,7 @@ jobs:
xcaddy version 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@v6 uses: goreleaser/goreleaser-action@9c156ee8a17a598857849441385a2041ef570552 # v6.3.0
with: with:
version: latest version: latest
args: release --clean --timeout 60m args: release --clean --timeout 60m

View File

@ -5,6 +5,9 @@ on:
release: release:
types: [published] types: [published]
permissions:
contents: read
jobs: jobs:
release: release:
name: Release Published name: Release Published
@ -13,12 +16,20 @@ jobs:
os: os:
- ubuntu-latest - ubuntu-latest
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
permissions:
contents: read
pull-requests: read
actions: write
steps: steps:
# See https://github.com/peter-evans/repository-dispatch # See https://github.com/peter-evans/repository-dispatch
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: Trigger event on caddyserver/dist - name: Trigger event on caddyserver/dist
uses: peter-evans/repository-dispatch@v3 uses: peter-evans/repository-dispatch@ff45666b9427631e3450c54a1bcbee4d9ff4d7c0 # v3.0.0
with: with:
token: ${{ secrets.REPO_DISPATCH_TOKEN }} token: ${{ secrets.REPO_DISPATCH_TOKEN }}
repository: caddyserver/dist repository: caddyserver/dist
@ -26,7 +37,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@v3 uses: peter-evans/repository-dispatch@ff45666b9427631e3450c54a1bcbee4d9ff4d7c0 # v3.0.0
with: with:
token: ${{ secrets.REPO_DISPATCH_TOKEN }} token: ${{ secrets.REPO_DISPATCH_TOKEN }}
repository: caddyserver/caddy-docker repository: caddyserver/caddy-docker

86
.github/workflows/scorecard.yml vendored Normal file
View File

@ -0,0 +1,86 @@
# This workflow uses actions that are not certified by GitHub. They are provided
# by a third-party and are governed by separate terms of service, privacy
# policy, and support documentation.
name: OpenSSF Scorecard supply-chain security
on:
# For Branch-Protection check. Only the default branch is supported. See
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
branch_protection_rule:
# To guarantee Maintained check is occasionally updated. See
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
schedule:
- cron: '20 2 * * 5'
push:
branches: [ "master", "2.*" ]
pull_request:
branches: [ "master", "2.*" ]
# Declare default permissions as read only.
permissions: read-all
jobs:
analysis:
name: Scorecard analysis
runs-on: ubuntu-latest
# `publish_results: true` only works when run from the default branch. conditional can be removed if disabled.
if: github.event.repository.default_branch == github.ref_name || github.event_name == 'pull_request'
permissions:
# Needed to upload the results to code-scanning dashboard.
security-events: write
# Needed to publish results and get a badge (see publish_results below).
id-token: write
# Uncomment the permissions below if installing in a private repository.
# contents: read
# actions: read
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
with:
egress-policy: audit
- name: "Checkout code"
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1
with:
results_file: results.sarif
results_format: sarif
# (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
# - you want to enable the Branch-Protection check on a *public* repository, or
# - you are installing Scorecard on a *private* repository
# To create the PAT, follow the steps in https://github.com/ossf/scorecard-action?tab=readme-ov-file#authentication-with-fine-grained-pat-optional.
# repo_token: ${{ secrets.SCORECARD_TOKEN }}
# Public repositories:
# - Publish results to OpenSSF REST API for easy access by consumers
# - Allows the repository to include the Scorecard badge.
# - See https://github.com/ossf/scorecard-action#publishing-results.
# For private repositories:
# - `publish_results` will always be set to `false`, regardless
# of the value entered here.
publish_results: true
# (Optional) Uncomment file_mode if you have a .gitattributes with files marked export-ignore
# file_mode: git
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
# format to the repository Actions tab.
- name: "Upload artifact"
uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1
with:
name: SARIF file
path: results.sarif
retention-days: 5
# Upload the results to GitHub's code scanning dashboard (optional).
# Commenting out will disable upload of results to your repo's Code Scanning dashboard
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0
with:
sarif_file: results.sarif

View File

@ -1,27 +1,15 @@
linters-settings: version: "2"
errcheck: run:
exclude-functions: issues-exit-code: 1
- fmt.* tests: false
- (go.uber.org/zap/zapcore.ObjectEncoder).AddObject output:
- (go.uber.org/zap/zapcore.ObjectEncoder).AddArray formats:
gci: text:
sections: path: stdout
- standard # Standard section: captures all standard packages. print-linter-name: true
- default # Default section: contains all imports that could not be matched to another section type. print-issued-lines: true
- 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 default: none
enable: enable:
- asasalint - asasalint
- asciicheck - asciicheck
@ -35,148 +23,96 @@ linters:
- errcheck - errcheck
- errname - errname
- exhaustive - exhaustive
- gci
- gofmt
- goimports
- gofumpt
- gosec - gosec
- gosimple
- govet - govet
- ineffassign
- importas - importas
- ineffassign
- misspell - misspell
- prealloc - prealloc
- promlinter - promlinter
- sloglint - sloglint
- sqlclosecheck - sqlclosecheck
- staticcheck - staticcheck
- tenv
- testableexamples - testableexamples
- testifylint - testifylint
- tparallel - tparallel
- typecheck
- unconvert - unconvert
- unused - unused
- wastedassign - wastedassign
- whitespace - whitespace
- zerologlint - zerologlint
# these are implicitly disabled: settings:
# - containedctx staticcheck:
# - contextcheck checks: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022", "-QF1006", "-QF1008"] # default, and exclude 1 more undesired check
# - cyclop errcheck:
# - depguard exclude-functions:
# - errchkjson - fmt.*
# - errorlint - (go.uber.org/zap/zapcore.ObjectEncoder).AddObject
# - exhaustruct - (go.uber.org/zap/zapcore.ObjectEncoder).AddArray
# - execinquery exhaustive:
# - exhaustruct ignore-enum-types: reflect.Kind|svc.Cmd
# - forbidigo exclusions:
# - forcetypeassert generated: lax
# - funlen presets:
# - ginkgolinter - comments
# - gocheckcompilerdirectives - common-false-positives
# - gochecknoglobals - legacy
# - gochecknoinits - std-error-handling
# - gochecksumtype rules:
# - gocognit - linters:
# - goconst - gosec
# - gocritic text: G115 # TODO: Either we should fix the issues or nuke the linter if it's bad
# - gocyclo - linters:
# - godot - gosec
# - godox text: G107 # we aren't calling unknown URL
# - goerr113 - linters:
# - goheader - gosec
# - gomnd text: G203 # as a web server that's expected to handle any template, this is totally in the hands of the user.
# - gomoddirectives - linters:
# - gomodguard - gosec
# - goprintffuncname text: G204 # we're shelling out to known commands, not relying on user-defined input.
# - gosmopolitan - linters:
# - grouper - gosec
# - inamedparam # the choice of weakrand is deliberate, hence the named import "weakrand"
# - interfacebloat path: modules/caddyhttp/reverseproxy/selectionpolicies.go
# - ireturn text: G404
# - lll - linters:
# - loggercheck - gosec
# - maintidx path: modules/caddyhttp/reverseproxy/streaming.go
# - makezero text: G404
# - mirror - linters:
# - musttag - dupl
# - nakedret path: modules/logging/filters.go
# - nestif - linters:
# - nilerr - dupl
# - nilnil path: modules/caddyhttp/matchers.go
# - nlreturn - linters:
# - noctx - dupl
# - nolintlint path: modules/caddyhttp/vars.go
# - nonamedreturns - linters:
# - nosprintfhostport - errcheck
# - paralleltest path: _test\.go
# - perfsprint paths:
# - predeclared - third_party$
# - protogetter - builtin$
# - reassign - examples$
# - revive formatters:
# - rowserrcheck enable:
# - stylecheck - gci
# - tagalign - gofmt
# - tagliatelle - gofumpt
# - testpackage - goimports
# - thelper settings:
# - unparam gci:
# - usestdlibvars sections:
# - varnamelen - standard # Standard section: captures all standard packages.
# - wrapcheck - default # Default section: contains all imports that could not be matched to another section type.
# - wsl - 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.
run: custom-order: true
# default concurrency is a available CPU number. exclusions:
# concurrency: 4 # explicitly omit this value to fully utilize available resources. generated: lax
timeout: 5m paths:
issues-exit-code: 1 - third_party$
tests: false - builtin$
- examples$
# output configuration options
output:
formats:
- format: 'colored-line-number'
print-issued-lines: true
print-linter-name: true
issues:
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
- text: 'G107' # G107: Url provided to HTTP request as taint input
linters:
- gosec
# 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
linters:
- gosec
# we're shelling out to known commands, not relying on user-defined input.
- text: 'G204' # G204: Audit use of command execution
linters:
- gosec
# the choice of weakrand is deliberate, hence the named import "weakrand"
- path: modules/caddyhttp/reverseproxy/selectionpolicies.go
text: 'G404' # G404: Insecure random number source (rand)
linters:
- gosec
- path: modules/caddyhttp/reverseproxy/streaming.go
text: 'G404' # G404: Insecure random number source (rand)
linters:
- 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

20
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,20 @@
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.16.3
hooks:
- id: gitleaks
- repo: https://github.com/golangci/golangci-lint
rev: v1.52.2
hooks:
- id: golangci-lint-config-verify
- id: golangci-lint
- id: golangci-lint-fmt
- repo: https://github.com/jumanjihouse/pre-commit-hooks
rev: 3.0.0
hooks:
- id: shellcheck
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: end-of-file-fixer
- id: trailing-whitespace

View File

@ -14,6 +14,7 @@
<p align="center">Caddy is an extensible server platform that uses TLS by default.</p> <p align="center">Caddy is an extensible server platform that uses TLS by default.</p>
<p align="center"> <p align="center">
<a href="https://github.com/caddyserver/caddy/actions/workflows/ci.yml"><img src="https://github.com/caddyserver/caddy/actions/workflows/ci.yml/badge.svg"></a> <a href="https://github.com/caddyserver/caddy/actions/workflows/ci.yml"><img src="https://github.com/caddyserver/caddy/actions/workflows/ci.yml/badge.svg"></a>
<a href="https://www.bestpractices.dev/projects/7141"><img src="https://www.bestpractices.dev/projects/7141/badge"></a>
<a href="https://pkg.go.dev/github.com/caddyserver/caddy/v2"><img src="https://img.shields.io/badge/godoc-reference-%23007d9c.svg"></a> <a href="https://pkg.go.dev/github.com/caddyserver/caddy/v2"><img src="https://img.shields.io/badge/godoc-reference-%23007d9c.svg"></a>
<br> <br>
<a href="https://x.com/caddyserver" title="@caddyserver on Twitter"><img src="https://img.shields.io/twitter/follow/caddyserver" alt="@caddyserver on Twitter"></a> <a href="https://x.com/caddyserver" title="@caddyserver on Twitter"><img src="https://img.shields.io/twitter/follow/caddyserver" alt="@caddyserver on Twitter"></a>

View File

@ -221,7 +221,8 @@ func (admin *AdminConfig) newAdminHandler(addr NetworkAddress, remote bool, _ Co
if remote { if remote {
muxWrap.remoteControl = admin.Remote muxWrap.remoteControl = admin.Remote
} else { } else {
muxWrap.enforceHost = !addr.isWildcardInterface() // see comment in allowedOrigins() as to why we disable the host check for unix/fd networks
muxWrap.enforceHost = !addr.isWildcardInterface() && !addr.IsUnixNetwork() && !addr.IsFdNetwork()
muxWrap.allowedOrigins = admin.allowedOrigins(addr) muxWrap.allowedOrigins = admin.allowedOrigins(addr)
muxWrap.enforceOrigin = admin.EnforceOrigin muxWrap.enforceOrigin = admin.EnforceOrigin
} }
@ -310,47 +311,43 @@ func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
for _, o := range admin.Origins { for _, o := range admin.Origins {
uniqueOrigins[o] = struct{}{} uniqueOrigins[o] = struct{}{}
} }
if admin.Origins == nil { // RFC 2616, Section 14.26:
// "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
// name for the service being requested, then the Host header field MUST
// be given with an empty value."
//
// UPDATE July 2023: Go broke this by patching a minor security bug in 1.20.6.
// Understandable, but frustrating. See:
// https://github.com/golang/go/issues/60374
// See also the discussion here:
// https://github.com/golang/go/issues/61431
//
// We can no longer conform to RFC 2616 Section 14.26 from either Go or curl
// in purity. (Curl allowed no host between 7.40 and 7.50, but now requires a
// bogus host; see https://superuser.com/a/925610.) If we disable Host/Origin
// security checks, the infosec community assures me that it is secure to do
// so, because:
//
// 1) Browsers do not allow access to unix sockets
// 2) DNS is irrelevant to unix sockets
//
// If either of those two statements ever fail to hold true, it is not the
// fault of Caddy.
//
// Thus, we do not fill out allowed origins and do not enforce Host
// requirements for unix sockets. Enforcing it leads to confusion and
// frustration, when UDS have their own permissions from the OS.
// Enforcing host requirements here is effectively security theater,
// and a false sense of security.
//
// See also the discussion in #6832.
if admin.Origins == nil && !addr.IsUnixNetwork() && !addr.IsFdNetwork() {
if addr.isLoopback() { if addr.isLoopback() {
if addr.IsUnixNetwork() || addr.IsFdNetwork() { uniqueOrigins[net.JoinHostPort("localhost", addr.port())] = struct{}{}
// RFC 2616, Section 14.26: uniqueOrigins[net.JoinHostPort("::1", addr.port())] = struct{}{}
// "A client MUST include a Host header field in all HTTP/1.1 request uniqueOrigins[net.JoinHostPort("127.0.0.1", addr.port())] = struct{}{}
// messages. If the requested URI does not include an Internet host } else {
// name for the service being requested, then the Host header field MUST
// be given with an empty value."
//
// UPDATE July 2023: Go broke this by patching a minor security bug in 1.20.6.
// Understandable, but frustrating. See:
// https://github.com/golang/go/issues/60374
// See also the discussion here:
// https://github.com/golang/go/issues/61431
//
// We can no longer conform to RFC 2616 Section 14.26 from either Go or curl
// in purity. (Curl allowed no host between 7.40 and 7.50, but now requires a
// bogus host; see https://superuser.com/a/925610.) If we disable Host/Origin
// security checks, the infosec community assures me that it is secure to do
// so, because:
// 1) Browsers do not allow access to unix sockets
// 2) DNS is irrelevant to unix sockets
//
// I am not quite ready to trust either of those external factors, so instead
// of disabling Host/Origin checks, we now allow specific Host values when
// accessing the admin endpoint over unix sockets. I definitely don't trust
// DNS (e.g. I don't trust 'localhost' to always resolve to the local host),
// and IP shouldn't even be used, but if it is for some reason, I think we can
// at least be reasonably assured that 127.0.0.1 and ::1 route to the local
// machine, meaning that a hypothetical browser origin would have to be on the
// local machine as well.
uniqueOrigins[""] = struct{}{}
uniqueOrigins["127.0.0.1"] = struct{}{}
uniqueOrigins["::1"] = struct{}{}
} else {
uniqueOrigins[net.JoinHostPort("localhost", addr.port())] = struct{}{}
uniqueOrigins[net.JoinHostPort("::1", addr.port())] = struct{}{}
uniqueOrigins[net.JoinHostPort("127.0.0.1", addr.port())] = struct{}{}
}
}
if !addr.IsUnixNetwork() && !addr.IsFdNetwork() {
uniqueOrigins[addr.JoinHostPort(0)] = struct{}{} uniqueOrigins[addr.JoinHostPort(0)] = struct{}{}
} }
} }
@ -427,6 +424,13 @@ func replaceLocalAdminServer(cfg *Config, ctx Context) error {
handler := cfg.Admin.newAdminHandler(addr, false, ctx) handler := cfg.Admin.newAdminHandler(addr, false, ctx)
// run the provisioners for loaded modules to make sure local
// state is properly re-initialized in the new admin server
err = cfg.Admin.provisionAdminRouters(ctx)
if err != nil {
return err
}
ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{}) ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{})
if err != nil { if err != nil {
return err return err
@ -548,6 +552,13 @@ func replaceRemoteAdminServer(ctx Context, cfg *Config) error {
// because we are using TLS authentication instead // because we are using TLS authentication instead
handler := cfg.Admin.newAdminHandler(addr, true, ctx) handler := cfg.Admin.newAdminHandler(addr, true, ctx)
// run the provisioners for loaded modules to make sure local
// state is properly re-initialized in the new admin server
err = cfg.Admin.provisionAdminRouters(ctx)
if err != nil {
return err
}
// 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
clientCertPool := x509.NewCertPool() clientCertPool := x509.NewCertPool()

View File

@ -19,6 +19,7 @@ import (
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
"fmt" "fmt"
"maps"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"reflect" "reflect"
@ -335,9 +336,7 @@ func TestAdminHandlerBuiltinRouteErrors(t *testing.T) {
func testGetMetricValue(labels map[string]string) float64 { func testGetMetricValue(labels map[string]string) float64 {
promLabels := prometheus.Labels{} promLabels := prometheus.Labels{}
for k, v := range labels { maps.Copy(promLabels, labels)
promLabels[k] = v
}
metric, err := adminMetrics.requestErrors.GetMetricWith(promLabels) metric, err := adminMetrics.requestErrors.GetMetricWith(promLabels)
if err != nil { if err != nil {
@ -377,9 +376,7 @@ func (m *mockModule) CaddyModule() ModuleInfo {
func TestNewAdminHandlerRouterRegistration(t *testing.T) { func TestNewAdminHandlerRouterRegistration(t *testing.T) {
originalModules := make(map[string]ModuleInfo) originalModules := make(map[string]ModuleInfo)
for k, v := range modules { maps.Copy(originalModules, modules)
originalModules[k] = v
}
defer func() { defer func() {
modules = originalModules modules = originalModules
}() }()
@ -479,9 +476,7 @@ func TestAdminRouterProvisioning(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
originalModules := make(map[string]ModuleInfo) originalModules := make(map[string]ModuleInfo)
for k, v := range modules { maps.Copy(originalModules, modules)
originalModules[k] = v
}
defer func() { defer func() {
modules = originalModules modules = originalModules
}() }()
@ -531,6 +526,7 @@ func TestAdminRouterProvisioning(t *testing.T) {
} }
func TestAllowedOriginsUnixSocket(t *testing.T) { func TestAllowedOriginsUnixSocket(t *testing.T) {
// see comment in allowedOrigins() as to why we do not fill out allowed origins for UDS
tests := []struct { tests := []struct {
name string name string
addr NetworkAddress addr NetworkAddress
@ -543,12 +539,8 @@ func TestAllowedOriginsUnixSocket(t *testing.T) {
Network: "unix", Network: "unix",
Host: "/tmp/caddy.sock", Host: "/tmp/caddy.sock",
}, },
origins: nil, // default origins origins: nil, // default origins
expectOrigins: []string{ expectOrigins: []string{},
"", // empty host as per RFC 2616
"127.0.0.1",
"::1",
},
}, },
{ {
name: "unix socket with custom origins", name: "unix socket with custom origins",
@ -578,7 +570,7 @@ func TestAllowedOriginsUnixSocket(t *testing.T) {
}, },
} }
for _, test := range tests { for i, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
admin := AdminConfig{ admin := AdminConfig{
Origins: test.origins, Origins: test.origins,
@ -592,7 +584,7 @@ func TestAllowedOriginsUnixSocket(t *testing.T) {
} }
if len(gotOrigins) != len(test.expectOrigins) { if len(gotOrigins) != len(test.expectOrigins) {
t.Errorf("Expected %d origins but got %d", len(test.expectOrigins), len(gotOrigins)) t.Errorf("%d: Expected %d origins but got %d", i, len(test.expectOrigins), len(gotOrigins))
return return
} }
@ -607,7 +599,7 @@ func TestAllowedOriginsUnixSocket(t *testing.T) {
} }
if !reflect.DeepEqual(expectMap, gotMap) { if !reflect.DeepEqual(expectMap, gotMap) {
t.Errorf("Origins mismatch.\nExpected: %v\nGot: %v", test.expectOrigins, gotOrigins) t.Errorf("%d: Origins mismatch.\nExpected: %v\nGot: %v", i, test.expectOrigins, gotOrigins)
} }
}) })
} }
@ -777,9 +769,7 @@ func (m *mockIssuerModule) CaddyModule() ModuleInfo {
func TestManageIdentity(t *testing.T) { func TestManageIdentity(t *testing.T) {
originalModules := make(map[string]ModuleInfo) originalModules := make(map[string]ModuleInfo)
for k, v := range modules { maps.Copy(originalModules, modules)
originalModules[k] = v
}
defer func() { defer func() {
modules = originalModules modules = originalModules
}() }()

144
caddy.go
View File

@ -81,13 +81,14 @@ type Config struct {
// associated value. // associated value.
AppsRaw ModuleMap `json:"apps,omitempty" caddy:"namespace="` AppsRaw ModuleMap `json:"apps,omitempty" caddy:"namespace="`
apps map[string]App apps map[string]App
storage certmagic.Storage storage certmagic.Storage
eventEmitter eventEmitter
cancelFunc context.CancelFunc cancelFunc context.CancelFunc
// filesystems is a dict of filesystems that will later be loaded from and added to. // fileSystems is a dict of fileSystems that will later be loaded from and added to.
filesystems FileSystems fileSystems FileSystems
} }
// App is a thing that Caddy runs. // App is a thing that Caddy runs.
@ -407,11 +408,23 @@ func run(newCfg *Config, start bool) (Context, error) {
return ctx, nil return ctx, nil
} }
defer func() {
// if newCfg fails to start completely, clean up the already provisioned modules
// partially copied from provisionContext
if err != nil {
globalMetrics.configSuccess.Set(0)
ctx.cfg.cancelFunc()
if currentCtx.cfg != nil {
certmagic.Default.Storage = currentCtx.cfg.storage
}
}
}()
// Provision any admin routers which may need to access // Provision any admin routers which may need to access
// some of the other apps at runtime // some of the other apps at runtime
err = ctx.cfg.Admin.provisionAdminRouters(ctx) err = ctx.cfg.Admin.provisionAdminRouters(ctx)
if err != nil { if err != nil {
globalMetrics.configSuccess.Set(0)
return ctx, err return ctx, err
} }
@ -437,14 +450,18 @@ func run(newCfg *Config, start bool) (Context, error) {
return nil return nil
}() }()
if err != nil { if err != nil {
globalMetrics.configSuccess.Set(0)
return ctx, err return ctx, err
} }
globalMetrics.configSuccess.Set(1) globalMetrics.configSuccess.Set(1)
globalMetrics.configSuccessTime.SetToCurrentTime() globalMetrics.configSuccessTime.SetToCurrentTime()
// TODO: This event is experimental and subject to change.
ctx.emitEvent("started", nil)
// now that the user's config is running, finish setting up anything else, // now that the user's config is running, finish setting up anything else,
// such as remote admin endpoint, config loader, etc. // such as remote admin endpoint, config loader, etc.
return ctx, finishSettingUp(ctx, ctx.cfg) err = finishSettingUp(ctx, ctx.cfg)
return ctx, err
} }
// provisionContext creates a new context from the given configuration and provisions // provisionContext creates a new context from the given configuration and provisions
@ -500,16 +517,8 @@ func provisionContext(newCfg *Config, replaceAdminServer bool) (Context, error)
return ctx, err return ctx, err
} }
// start the admin endpoint (and stop any prior one)
if replaceAdminServer {
err = replaceLocalAdminServer(newCfg, ctx)
if err != nil {
return ctx, fmt.Errorf("starting caddy administration endpoint: %v", err)
}
}
// create the new filesystem map // create the new filesystem map
newCfg.filesystems = &filesystems.FilesystemMap{} 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)
@ -539,6 +548,14 @@ func provisionContext(newCfg *Config, replaceAdminServer bool) (Context, error)
return ctx, err return ctx, err
} }
// start the admin endpoint (and stop any prior one)
if replaceAdminServer {
err = replaceLocalAdminServer(newCfg, ctx)
if err != nil {
return ctx, fmt.Errorf("starting caddy administration endpoint: %v", err)
}
}
// Load and Provision each app and their submodules // Load and Provision each app and their submodules
err = func() error { err = func() error {
for appName := range newCfg.AppsRaw { for appName := range newCfg.AppsRaw {
@ -696,6 +713,9 @@ func unsyncedStop(ctx Context) {
return return
} }
// TODO: This event is experimental and subject to change.
ctx.emitEvent("stopping", nil)
// stop each app // stop each app
for name, a := range ctx.cfg.apps { for name, a := range ctx.cfg.apps {
err := a.Stop() err := a.Stop()
@ -1038,6 +1058,98 @@ func Version() (simple, full string) {
return return
} }
// Event represents something that has happened or is happening.
// An Event value is not synchronized, so it should be copied if
// being used in goroutines.
//
// EXPERIMENTAL: Events are subject to change.
type Event struct {
// If non-nil, the event has been aborted, meaning
// propagation has stopped to other handlers and
// the code should stop what it was doing. Emitters
// may choose to use this as a signal to adjust their
// code path appropriately.
Aborted error
// The data associated with the event. Usually the
// original emitter will be the only one to set or
// change these values, but the field is exported
// so handlers can have full access if needed.
// However, this map is not synchronized, so
// handlers must not use this map directly in new
// goroutines; instead, copy the map to use it in a
// goroutine. Data may be nil.
Data map[string]any
id uuid.UUID
ts time.Time
name string
origin Module
}
// NewEvent creates a new event, but does not emit the event. To emit an
// event, call Emit() on the current instance of the caddyevents app insteaad.
//
// EXPERIMENTAL: Subject to change.
func NewEvent(ctx Context, name string, data map[string]any) (Event, error) {
id, err := uuid.NewRandom()
if err != nil {
return Event{}, fmt.Errorf("generating new event ID: %v", err)
}
name = strings.ToLower(name)
return Event{
Data: data,
id: id,
ts: time.Now(),
name: name,
origin: ctx.Module(),
}, nil
}
func (e Event) ID() uuid.UUID { return e.id }
func (e Event) Timestamp() time.Time { return e.ts }
func (e Event) Name() string { return e.name }
func (e Event) Origin() Module { return e.origin } // Returns the module that originated the event. May be nil, usually if caddy core emits the event.
// CloudEvent exports event e as a structure that, when
// serialized as JSON, is compatible with the
// CloudEvents spec.
func (e Event) CloudEvent() CloudEvent {
dataJSON, _ := json.Marshal(e.Data)
var source string
if e.Origin() == nil {
source = "caddy"
} else {
source = string(e.Origin().CaddyModule().ID)
}
return CloudEvent{
ID: e.id.String(),
Source: source,
SpecVersion: "1.0",
Type: e.name,
Time: e.ts,
DataContentType: "application/json",
Data: dataJSON,
}
}
// CloudEvent is a JSON-serializable structure that
// is compatible with the CloudEvents specification.
// See https://cloudevents.io.
// EXPERIMENTAL: Subject to change.
type CloudEvent struct {
ID string `json:"id"`
Source string `json:"source"`
SpecVersion string `json:"specversion"`
Type string `json:"type"`
Time time.Time `json:"time"`
DataContentType string `json:"datacontenttype,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
// ErrEventAborted cancels an event.
var ErrEventAborted = errors.New("event aborted")
// ActiveContext returns the currently-active context. // ActiveContext returns the currently-active context.
// This function is experimental and might be changed // This function is experimental and might be changed
// or removed in the future. // or removed in the future.

View File

@ -15,6 +15,7 @@
package caddy package caddy
import ( import (
"context"
"testing" "testing"
"time" "time"
) )
@ -72,3 +73,21 @@ func TestParseDuration(t *testing.T) {
} }
} }
} }
func TestEvent_CloudEvent_NilOrigin(t *testing.T) {
ctx, _ := NewContext(Context{Context: context.Background()}) // module will be nil by default
event, err := NewEvent(ctx, "started", nil)
if err != nil {
t.Fatalf("NewEvent() error = %v", err)
}
// This should not panic
ce := event.CloudEvent()
if ce.Source != "caddy" {
t.Errorf("Expected CloudEvent Source to be 'caddy', got '%s'", ce.Source)
}
if ce.Type != "started" {
t.Errorf("Expected CloudEvent Type to be 'started', got '%s'", ce.Type)
}
}

View File

@ -68,7 +68,7 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
// TODO: also perform this check on imported files // TODO: also perform this check on imported files
func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) { func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) {
// replace windows-style newlines to normalize comparison // replace windows-style newlines to normalize comparison
normalizedBody := bytes.Replace(body, []byte("\r\n"), []byte("\n"), -1) normalizedBody := bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n"))
formatted := Format(normalizedBody) formatted := Format(normalizedBody)
if bytes.Equal(formatted, normalizedBody) { if bytes.Equal(formatted, normalizedBody) {

View File

@ -94,7 +94,7 @@ func Format(input []byte) []byte {
} }
// detect whether we have the start of a heredoc // detect whether we have the start of a heredoc
if !quoted && !(heredoc != heredocClosed || heredocEscaped) && if !quoted && (heredoc == heredocClosed && !heredocEscaped) &&
space && last == '<' && ch == '<' { space && last == '<' && ch == '<' {
write(ch) write(ch)
heredoc = heredocOpening heredoc = heredocOpening

View File

@ -137,7 +137,7 @@ 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 !(quoted || btQuoted) && !(inHeredoc || heredocEscaped) && if (!quoted && !btQuoted) && (!inHeredoc && !heredocEscaped) &&
len(val) > 1 && string(val[:2]) == "<<" { len(val) > 1 && string(val[:2]) == "<<" {
// a space means it's just a regular token and not a heredoc // a space means it's just a regular token and not a heredoc
if ch == ' ' { if ch == ' ' {
@ -323,7 +323,8 @@ func (l *lexer) finalizeHeredoc(val []rune, marker string) ([]rune, error) {
// if the padding doesn't match exactly at the start then we can't safely strip // if the padding doesn't match exactly at the start then we can't safely strip
if index != 0 { if index != 0 {
return nil, fmt.Errorf("mismatched leading whitespace in heredoc <<%s on line #%d [%s], expected whitespace [%s] to match the closing marker", marker, l.line+lineNum+1, lineText, paddingToStrip) cleanLineText := strings.TrimRight(lineText, "\r\n")
return nil, fmt.Errorf("mismatched leading whitespace in heredoc <<%s on line #%d [%s], expected whitespace [%s] to match the closing marker", marker, l.line+lineNum+1, cleanLineText, paddingToStrip)
} }
// strip, then append the line, with the newline, to the output. // strip, then append the line, with the newline, to the output.

View File

@ -15,6 +15,7 @@
package httpcaddyfile package httpcaddyfile
import ( import (
"encoding/json"
"fmt" "fmt"
"html" "html"
"net/http" "net/http"
@ -129,6 +130,9 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
var reusePrivateKeys bool var reusePrivateKeys bool
var forceAutomate bool var forceAutomate bool
// Track which DNS challenge options are set
var dnsOptionsSet []string
firstLine := h.RemainingArgs() firstLine := h.RemainingArgs()
switch len(firstLine) { switch len(firstLine) {
case 0: case 0:
@ -349,6 +353,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
if acmeIssuer.Challenges.DNS == nil { if acmeIssuer.Challenges.DNS == nil {
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
} }
dnsOptionsSet = append(dnsOptionsSet, "resolvers")
acmeIssuer.Challenges.DNS.Resolvers = args acmeIssuer.Challenges.DNS.Resolvers = args
case "propagation_delay": case "propagation_delay":
@ -370,6 +375,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
if acmeIssuer.Challenges.DNS == nil { if acmeIssuer.Challenges.DNS == nil {
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
} }
dnsOptionsSet = append(dnsOptionsSet, "propagation_delay")
acmeIssuer.Challenges.DNS.PropagationDelay = caddy.Duration(delay) acmeIssuer.Challenges.DNS.PropagationDelay = caddy.Duration(delay)
case "propagation_timeout": case "propagation_timeout":
@ -397,6 +403,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
if acmeIssuer.Challenges.DNS == nil { if acmeIssuer.Challenges.DNS == nil {
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
} }
dnsOptionsSet = append(dnsOptionsSet, "propagation_timeout")
acmeIssuer.Challenges.DNS.PropagationTimeout = caddy.Duration(timeout) acmeIssuer.Challenges.DNS.PropagationTimeout = caddy.Duration(timeout)
case "dns_ttl": case "dns_ttl":
@ -418,6 +425,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
if acmeIssuer.Challenges.DNS == nil { if acmeIssuer.Challenges.DNS == nil {
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
} }
dnsOptionsSet = append(dnsOptionsSet, "dns_ttl")
acmeIssuer.Challenges.DNS.TTL = caddy.Duration(ttl) acmeIssuer.Challenges.DNS.TTL = caddy.Duration(ttl)
case "dns_challenge_override_domain": case "dns_challenge_override_domain":
@ -434,6 +442,7 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
if acmeIssuer.Challenges.DNS == nil { if acmeIssuer.Challenges.DNS == nil {
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig) acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
} }
dnsOptionsSet = append(dnsOptionsSet, "dns_challenge_override_domain")
acmeIssuer.Challenges.DNS.OverrideDomain = arg[0] acmeIssuer.Challenges.DNS.OverrideDomain = arg[0]
case "ca_root": case "ca_root":
@ -469,6 +478,18 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
} }
} }
// Validate DNS challenge config: any DNS challenge option except "dns" requires a DNS provider
if acmeIssuer != nil && acmeIssuer.Challenges != nil && acmeIssuer.Challenges.DNS != nil {
dnsCfg := acmeIssuer.Challenges.DNS
providerSet := dnsCfg.ProviderRaw != nil || h.Option("dns") != nil
if len(dnsOptionsSet) > 0 && !providerSet {
return nil, h.Errf(
"setting DNS challenge options [%s] requires a DNS provider (set with the 'dns' subdirective or 'acme_dns' global option)",
strings.Join(dnsOptionsSet, ", "),
)
}
}
// a naked tls directive is not allowed // a naked tls directive is not allowed
if len(firstLine) == 0 && !hasBlock { if len(firstLine) == 0 && !hasBlock {
return nil, h.ArgErr() return nil, h.ArgErr()
@ -843,13 +864,18 @@ func parseHandleErrors(h Helper) ([]ConfigValue, error) {
return nil, h.Errf("segment was not parsed as a subroute") return nil, h.Errf("segment was not parsed as a subroute")
} }
// wrap the subroutes
wrappingRoute := caddyhttp.Route{
HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subroute, "handler", "subroute", nil)},
}
subroute = &caddyhttp.Subroute{
Routes: []caddyhttp.Route{wrappingRoute},
}
if expression != "" { if expression != "" {
statusMatcher := caddy.ModuleMap{ statusMatcher := caddy.ModuleMap{
"expression": h.JSON(caddyhttp.MatchExpression{Expr: expression}), "expression": h.JSON(caddyhttp.MatchExpression{Expr: expression}),
} }
for i := range subroute.Routes { subroute.Routes[0].MatcherSetsRaw = []caddy.ModuleMap{statusMatcher}
subroute.Routes[i].MatcherSetsRaw = []caddy.ModuleMap{statusMatcher}
}
} }
return []ConfigValue{ return []ConfigValue{
{ {
@ -1160,6 +1186,11 @@ func parseLogSkip(h Helper) (caddyhttp.MiddlewareHandler, error) {
if h.NextArg() { if h.NextArg() {
return nil, h.ArgErr() return nil, h.ArgErr()
} }
if h.NextBlock(0) {
return nil, h.Err("log_skip directive does not accept blocks")
}
return caddyhttp.VarsMiddleware{"log_skip": true}, nil return caddyhttp.VarsMiddleware{"log_skip": true}, nil
} }

View File

@ -16,6 +16,7 @@ package httpcaddyfile
import ( import (
"encoding/json" "encoding/json"
"maps"
"net" "net"
"slices" "slices"
"sort" "sort"
@ -173,10 +174,12 @@ func RegisterDirectiveOrder(dir string, position Positional, standardDir string)
if d != standardDir { if d != standardDir {
continue continue
} }
if position == Before { switch position {
case Before:
newOrder = append(newOrder[:i], append([]string{dir}, newOrder[i:]...)...) newOrder = append(newOrder[:i], append([]string{dir}, newOrder[i:]...)...)
} else if position == After { case After:
newOrder = append(newOrder[:i+1], append([]string{dir}, newOrder[i+1:]...)...) newOrder = append(newOrder[:i+1], append([]string{dir}, newOrder[i+1:]...)...)
case First, Last:
} }
break break
} }
@ -365,9 +368,7 @@ func parseSegmentAsConfig(h Helper) ([]ConfigValue, error) {
// copy existing matcher definitions so we can augment // copy existing matcher definitions so we can augment
// new ones that are defined only in this scope // new ones that are defined only in this scope
matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs)) matcherDefs := make(map[string]caddy.ModuleMap, len(h.matcherDefs))
for key, val := range h.matcherDefs { maps.Copy(matcherDefs, h.matcherDefs)
matcherDefs[key] = val
}
// find and extract any embedded matcher definitions in this scope // find and extract any embedded matcher definitions in this scope
for i := 0; i < len(segments); i++ { for i := 0; i < len(segments); i++ {
@ -483,12 +484,29 @@ func sortRoutes(routes []ConfigValue) {
// we can only confidently compare path lengths if both // we can only confidently compare path lengths if both
// directives have a single path to match (issue #5037) // directives have a single path to match (issue #5037)
if iPathLen > 0 && jPathLen > 0 { if iPathLen > 0 && jPathLen > 0 {
// trim the trailing wildcard if there is one
iPathTrimmed := strings.TrimSuffix(iPM[0], "*")
jPathTrimmed := strings.TrimSuffix(jPM[0], "*")
// if both paths are the same except for a trailing wildcard, // if both paths are the same except for a trailing wildcard,
// sort by the shorter path first (which is more specific) // sort by the shorter path first (which is more specific)
if strings.TrimSuffix(iPM[0], "*") == strings.TrimSuffix(jPM[0], "*") { if iPathTrimmed == jPathTrimmed {
return iPathLen < jPathLen return iPathLen < jPathLen
} }
// we use the trimmed length to compare the paths
// https://github.com/caddyserver/caddy/issues/7012#issuecomment-2870142195
// credit to https://github.com/Hellio404
// for sorts with many items, mixing matchers w/ and w/o wildcards will confuse the sort and result in incorrect orders
iPathLen = len(iPathTrimmed)
jPathLen = len(jPathTrimmed)
// if both paths have the same length, sort lexically
// https://github.com/caddyserver/caddy/pull/7015#issuecomment-2871993588
if iPathLen == jPathLen {
return iPathTrimmed < jPathTrimmed
}
// sort most-specific (longest) path first // sort most-specific (longest) path first
return iPathLen > jPathLen return iPathLen > jPathLen
} }

View File

@ -633,12 +633,6 @@ func (st *ServerType) serversFromPairings(
srv.AutoHTTPS = new(caddyhttp.AutoHTTPSConfig) 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
} }
} }
@ -706,16 +700,6 @@ func (st *ServerType) serversFromPairings(
return specificity(iLongestHost) > specificity(jLongestHost) return specificity(iLongestHost) > specificity(jLongestHost)
}) })
// collect all hosts that have a wildcard in them
wildcardHosts := []string{}
for _, sblock := range p.serverBlocks {
for _, addr := range sblock.parsedKeys {
if strings.HasPrefix(addr.Host, "*.") {
wildcardHosts = append(wildcardHosts, addr.Host[2:])
}
}
}
var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool
autoHTTPSWillAddConnPolicy := srv.AutoHTTPS == nil || !srv.AutoHTTPS.Disabled autoHTTPSWillAddConnPolicy := srv.AutoHTTPS == nil || !srv.AutoHTTPS.Disabled
@ -801,7 +785,13 @@ func (st *ServerType) serversFromPairings(
cp.FallbackSNI = fallbackSNI cp.FallbackSNI = fallbackSNI
} }
// only append this policy if it actually changes something // only append this policy if it actually changes something,
// or if the configuration explicitly automates certs for
// these names (this is necessary to hoist a connection policy
// above one that may manually load a wildcard cert that would
// otherwise clobber the automated one; the code that appends
// policies that manually load certs comes later, so they're
// lower in the list)
if !cp.SettingsEmpty() || mapContains(forceAutomatedNames, hosts) { if !cp.SettingsEmpty() || mapContains(forceAutomatedNames, hosts) {
srv.TLSConnPolicies = append(srv.TLSConnPolicies, cp) srv.TLSConnPolicies = append(srv.TLSConnPolicies, cp)
hasCatchAllTLSConnPolicy = len(hosts) == 0 hasCatchAllTLSConnPolicy = len(hosts) == 0
@ -841,18 +831,6 @@ func (st *ServerType) serversFromPairings(
addressQualifiesForTLS = true addressQualifiesForTLS = true
} }
// If prefer wildcard is enabled, then we add hosts that are
// already covered by the wildcard to the skip list
if addressQualifiesForTLS && srv.AutoHTTPS != nil && srv.AutoHTTPS.PreferWildcard {
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.SkipCerts = append(srv.AutoHTTPS.SkipCerts, addr.Host)
}
}
// 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
// may not need to add one for this server // may not need to add one for this server
autoHTTPSWillAddConnPolicy = autoHTTPSWillAddConnPolicy && autoHTTPSWillAddConnPolicy = autoHTTPSWillAddConnPolicy &&
@ -1083,11 +1061,40 @@ func consolidateConnPolicies(cps caddytls.ConnectionPolicies) (caddytls.Connecti
// 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(cps[i], cps[j]) { if reflect.DeepEqual(cps[i], cps[j]) {
cps = append(cps[:j], cps[j+1:]...) cps = slices.Delete(cps, j, j+1)
i-- i--
break break
} }
// as a special case, if there are adjacent TLS conn policies that are identical except
// by their matchers, and the matchers are specifically just ServerName ("sni") matchers
// (by far the most common), we can combine them into a single policy
if i == j-1 && len(cps[i].MatchersRaw) == 1 && len(cps[j].MatchersRaw) == 1 {
if iSNIMatcherJSON, ok := cps[i].MatchersRaw["sni"]; ok {
if jSNIMatcherJSON, ok := cps[j].MatchersRaw["sni"]; ok {
// position of policies and the matcher criteria check out; if settings are
// the same, then we can combine the policies; we have to unmarshal and
// remarshal the matchers though
if cps[i].SettingsEqual(*cps[j]) {
var iSNIMatcher caddytls.MatchServerName
if err := json.Unmarshal(iSNIMatcherJSON, &iSNIMatcher); err == nil {
var jSNIMatcher caddytls.MatchServerName
if err := json.Unmarshal(jSNIMatcherJSON, &jSNIMatcher); err == nil {
iSNIMatcher = append(iSNIMatcher, jSNIMatcher...)
cps[i].MatchersRaw["sni"], err = json.Marshal(iSNIMatcher)
if err != nil {
return nil, fmt.Errorf("recombining SNI matchers: %v", err)
}
cps = slices.Delete(cps, j, j+1)
i--
break
}
}
}
}
}
}
// if they have the same matcher, try to reconcile each field: either they must // if they have the same matcher, try to reconcile each field: either they must
// be identical, or we have to be able to combine them safely // be identical, or we have to be able to combine them safely
if reflect.DeepEqual(cps[i].MatchersRaw, cps[j].MatchersRaw) { if reflect.DeepEqual(cps[i].MatchersRaw, cps[j].MatchersRaw) {
@ -1189,12 +1196,13 @@ func consolidateConnPolicies(cps caddytls.ConnectionPolicies) (caddytls.Connecti
} }
} }
cps = append(cps[:j], cps[j+1:]...) cps = slices.Delete(cps, j, j+1)
i-- i--
break break
} }
} }
} }
return cps, nil return cps, nil
} }

View File

@ -92,11 +92,9 @@ func (st ServerType) buildTLSApp(
tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, catchAllAP) tlsApp.Automation.Policies = append(tlsApp.Automation.Policies, catchAllAP)
} }
// collect all hosts that have a wildcard in them, and arent HTTP var wildcardHosts []string // collect all hosts that have a wildcard in them, and aren't HTTP
wildcardHosts := []string{} forcedAutomatedNames := make(map[string]struct{}) // explicitly configured to be automated, even if covered by a wildcard
// hosts that have been explicitly marked to be automated,
// even if covered by another wildcard
forcedAutomatedNames := make(map[string]struct{})
for _, p := range pairings { for _, p := range pairings {
var addresses []string var addresses []string
for _, addressWithProtocols := range p.addressesWithProtocols { for _, addressWithProtocols := range p.addressesWithProtocols {
@ -153,7 +151,7 @@ func (st ServerType) buildTLSApp(
ap.OnDemand = true ap.OnDemand = true
} }
// collect hosts that are forced to be automated // collect hosts that are forced to have certs automated for their specific name
if _, ok := sblock.pile["tls.force_automate"]; ok { if _, ok := sblock.pile["tls.force_automate"]; ok {
for _, host := range sblockHosts { for _, host := range sblockHosts {
forcedAutomatedNames[host] = struct{}{} forcedAutomatedNames[host] = struct{}{}
@ -375,7 +373,9 @@ func (st ServerType) buildTLSApp(
return nil, warnings, err return nil, warnings, err
} }
for _, cfg := range ech.Configs { for _, cfg := range ech.Configs {
ap.SubjectsRaw = append(ap.SubjectsRaw, cfg.PublicName) if cfg.PublicName != "" {
ap.SubjectsRaw = append(ap.SubjectsRaw, cfg.PublicName)
}
} }
if tlsApp.Automation == nil { if tlsApp.Automation == nil {
tlsApp.Automation = new(caddytls.AutomationConfig) tlsApp.Automation = new(caddytls.AutomationConfig)

View File

@ -281,7 +281,7 @@ func validateTestPrerequisites(tc *Tester) error {
tc.t.Cleanup(func() { tc.t.Cleanup(func() {
os.Remove(f.Name()) os.Remove(f.Name())
}) })
if _, err := f.WriteString(fmt.Sprintf(initConfig, tc.config.AdminPort)); err != nil { if _, err := fmt.Fprintf(f, initConfig, tc.config.AdminPort); err != nil {
return err return err
} }

View File

@ -12,13 +12,14 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddytest"
"github.com/mholt/acmez/v3" "github.com/mholt/acmez/v3"
"github.com/mholt/acmez/v3/acme" "github.com/mholt/acmez/v3/acme"
smallstepacme "github.com/smallstep/certificates/acme" smallstepacme "github.com/smallstep/certificates/acme"
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/exp/zapslog" "go.uber.org/zap/exp/zapslog"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddytest"
) )
const acmeChallengePort = 9081 const acmeChallengePort = 9081

View File

@ -9,11 +9,12 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/caddyserver/caddy/v2/caddytest"
"github.com/mholt/acmez/v3" "github.com/mholt/acmez/v3"
"github.com/mholt/acmez/v3/acme" "github.com/mholt/acmez/v3/acme"
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/exp/zapslog" "go.uber.org/zap/exp/zapslog"
"github.com/caddyserver/caddy/v2/caddytest"
) )
func TestACMEServerDirectory(t *testing.T) { func TestACMEServerDirectory(t *testing.T) {

View File

@ -0,0 +1,72 @@
{
pki {
ca custom-ca {
name "Custom CA"
}
}
}
acme.example.com {
acme_server {
ca custom-ca
allow {
domains host-1.internal.example.com host-2.internal.example.com
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"acme.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"ca": "custom-ca",
"handler": "acme_server",
"policy": {
"allow": {
"domains": [
"host-1.internal.example.com",
"host-2.internal.example.com"
]
}
}
}
]
}
]
}
],
"terminal": true
}
]
}
}
},
"pki": {
"certificate_authorities": {
"custom-ca": {
"name": "Custom CA"
}
}
}
}
}

View File

@ -0,0 +1,80 @@
{
pki {
ca custom-ca {
name "Custom CA"
}
}
}
acme.example.com {
acme_server {
ca custom-ca
allow {
domains host-1.internal.example.com host-2.internal.example.com
}
deny {
domains dc.internal.example.com
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"acme.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"ca": "custom-ca",
"handler": "acme_server",
"policy": {
"allow": {
"domains": [
"host-1.internal.example.com",
"host-2.internal.example.com"
]
},
"deny": {
"domains": [
"dc.internal.example.com"
]
}
}
}
]
}
]
}
],
"terminal": true
}
]
}
}
},
"pki": {
"certificate_authorities": {
"custom-ca": {
"name": "Custom CA"
}
}
}
}
}

View File

@ -0,0 +1,71 @@
{
pki {
ca custom-ca {
name "Custom CA"
}
}
}
acme.example.com {
acme_server {
ca custom-ca
deny {
domains dc.internal.example.com
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"acme.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"ca": "custom-ca",
"handler": "acme_server",
"policy": {
"deny": {
"domains": [
"dc.internal.example.com"
]
}
}
}
]
}
]
}
],
"terminal": true
}
]
}
}
},
"pki": {
"certificate_authorities": {
"custom-ca": {
"name": "Custom CA"
}
}
}
}
}

View File

@ -0,0 +1,12 @@
example.com
handle {
respond "one"
}
example.com
handle {
respond "two"
}
----------
Caddyfile:6: unrecognized directive: example.com
Did you mean to define a second site? If so, you must use curly braces around each site to separate their configurations.

View File

@ -0,0 +1,9 @@
:8080 {
respond "one"
}
:8080 {
respond "two"
}
----------
ambiguous site definition: :8080

View File

@ -1,109 +0,0 @@
{
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": {
"skip_certificates": [
"foo.example.com"
],
"prefer_wildcard": true
}
}
}
},
"tls": {
"automation": {
"policies": [
{
"subjects": [
"*.example.com"
],
"issuers": [
{
"challenges": {
"dns": {
"provider": {
"name": "mock"
}
}
},
"module": "acme"
}
]
}
]
}
}
}
}

View File

@ -1,268 +0,0 @@
{
auto_https prefer_wildcard
}
# Covers two domains
*.one.example.com {
tls {
dns mock
}
respond "one fallback"
}
# Is covered, should not get its own AP
foo.one.example.com {
respond "foo one"
}
# This one has its own tls config so it doesn't get covered (escape hatch)
bar.one.example.com {
respond "bar one"
tls bar@bar.com
}
# Covers nothing but AP gets consolidated with the first
*.two.example.com {
tls {
dns mock
}
respond "two fallback"
}
# Is HTTP so it should not cover
http://*.three.example.com {
respond "three fallback"
}
# Has no wildcard coverage so it gets an AP
foo.three.example.com {
respond "foo three"
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"foo.three.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "foo three",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
},
{
"match": [
{
"host": [
"foo.one.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "foo one",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
},
{
"match": [
{
"host": [
"bar.one.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "bar one",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
},
{
"match": [
{
"host": [
"*.one.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "one fallback",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
},
{
"match": [
{
"host": [
"*.two.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "two fallback",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"automatic_https": {
"skip_certificates": [
"foo.one.example.com",
"bar.one.example.com"
],
"prefer_wildcard": true
}
},
"srv1": {
"listen": [
":80"
],
"routes": [
{
"match": [
{
"host": [
"*.three.example.com"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "three fallback",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"automatic_https": {
"prefer_wildcard": true
}
}
}
},
"tls": {
"automation": {
"policies": [
{
"subjects": [
"foo.three.example.com"
]
},
{
"subjects": [
"bar.one.example.com"
],
"issuers": [
{
"email": "bar@bar.com",
"module": "acme"
},
{
"ca": "https://acme.zerossl.com/v2/DV90",
"email": "bar@bar.com",
"module": "acme"
}
]
},
{
"subjects": [
"*.one.example.com",
"*.two.example.com"
],
"issuers": [
{
"challenges": {
"dns": {
"provider": {
"name": "mock"
}
}
},
"module": "acme"
}
]
}
]
}
}
}
}

View File

@ -0,0 +1,5 @@
handle
respond "should not work"
----------
Caddyfile:1: parsed 'handle' as a site address, but it is a known directive; directives must appear in a site block

View File

@ -0,0 +1,12 @@
{
servers {
srv0 {
listen :8080
}
srv1 {
listen :8080
}
}
}
----------
parsing caddyfile tokens for 'servers': unrecognized servers option 'srv0', at Caddyfile:3

View File

@ -106,20 +106,29 @@ example.com {
"handler": "subroute", "handler": "subroute",
"routes": [ "routes": [
{ {
"group": "group0",
"handle": [ "handle": [
{ {
"handler": "rewrite", "handler": "subroute",
"uri": "/{http.error.status_code}.html" "routes": [
} {
] "group": "group0",
}, "handle": [
{ {
"handle": [ "handler": "rewrite",
{ "uri": "/{http.error.status_code}.html"
"handler": "file_server", }
"hide": [ ]
"./Caddyfile" },
{
"handle": [
{
"handler": "file_server",
"hide": [
"./Caddyfile"
]
}
]
}
] ]
} }
] ]

View File

@ -165,8 +165,17 @@ bar.localhost {
{ {
"handle": [ "handle": [
{ {
"body": "404 or 410 error", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "404 or 410 error",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [
@ -178,8 +187,17 @@ bar.localhost {
{ {
"handle": [ "handle": [
{ {
"body": "Error In range [500 .. 599]", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Error In range [500 .. 599]",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [
@ -208,8 +226,17 @@ bar.localhost {
{ {
"handle": [ "handle": [
{ {
"body": "404 or 410 error from second site", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "404 or 410 error from second site",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [
@ -221,8 +248,17 @@ bar.localhost {
{ {
"handle": [ "handle": [
{ {
"body": "Error In range [500 .. 599] from second site", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Error In range [500 .. 599] from second site",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [

View File

@ -96,8 +96,17 @@ localhost:3010 {
{ {
"handle": [ "handle": [
{ {
"body": "Error in the [400 .. 499] range", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Error in the [400 .. 499] range",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [

View File

@ -116,8 +116,17 @@ localhost:2099 {
{ {
"handle": [ "handle": [
{ {
"body": "Error in the [400 .. 499] range", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Error in the [400 .. 499] range",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [
@ -129,8 +138,17 @@ localhost:2099 {
{ {
"handle": [ "handle": [
{ {
"body": "Error code is equal to 500 or in the [300..399] range", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Error code is equal to 500 or in the [300..399] range",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [

View File

@ -96,8 +96,17 @@ localhost:3010 {
{ {
"handle": [ "handle": [
{ {
"body": "404 or 410 error", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "404 or 410 error",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [

View File

@ -116,8 +116,17 @@ localhost:2099 {
{ {
"handle": [ "handle": [
{ {
"body": "Error in the [400 .. 499] range", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Error in the [400 .. 499] range",
"handler": "static_response"
}
]
}
]
} }
], ],
"match": [ "match": [
@ -129,8 +138,17 @@ localhost:2099 {
{ {
"handle": [ "handle": [
{ {
"body": "Fallback route: code outside the [400..499] range", "handler": "subroute",
"handler": "static_response" "routes": [
{
"handle": [
{
"body": "Fallback route: code outside the [400..499] range",
"handler": "static_response"
}
]
}
]
} }
] ]
} }

View File

@ -0,0 +1,260 @@
{
http_port 2099
}
localhost:2099 {
root * /var/www/
file_server
handle_errors 404 {
handle /en/* {
respond "not found" 404
}
handle /es/* {
respond "no encontrado"
}
handle {
respond "default not found"
}
}
handle_errors {
handle /en/* {
respond "English error"
}
handle /es/* {
respond "Spanish error"
}
handle {
respond "Default error"
}
}
}
----------
{
"apps": {
"http": {
"http_port": 2099,
"servers": {
"srv0": {
"listen": [
":2099"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"handler": "vars",
"root": "/var/www/"
},
{
"handler": "file_server",
"hide": [
"./Caddyfile"
]
}
]
}
]
}
],
"terminal": true
}
],
"errors": {
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"handler": "subroute",
"routes": [
{
"group": "group3",
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "not found",
"handler": "static_response",
"status_code": 404
}
]
}
]
}
],
"match": [
{
"path": [
"/en/*"
]
}
]
},
{
"group": "group3",
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "no encontrado",
"handler": "static_response"
}
]
}
]
}
],
"match": [
{
"path": [
"/es/*"
]
}
]
},
{
"group": "group3",
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "default not found",
"handler": "static_response"
}
]
}
]
}
]
}
]
}
],
"match": [
{
"expression": "{http.error.status_code} in [404]"
}
]
},
{
"handle": [
{
"handler": "subroute",
"routes": [
{
"group": "group8",
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "English error",
"handler": "static_response"
}
]
}
]
}
],
"match": [
{
"path": [
"/en/*"
]
}
]
},
{
"group": "group8",
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "Spanish error",
"handler": "static_response"
}
]
}
]
}
],
"match": [
{
"path": [
"/es/*"
]
}
]
},
{
"group": "group8",
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "Default error",
"handler": "static_response"
}
]
}
]
}
]
}
]
}
]
}
]
}
],
"terminal": true
}
]
}
}
}
}
}
}

View File

@ -0,0 +1,41 @@
:80
handle {
respond <<END
line1
line2
END
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":80"
],
"routes": [
{
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": " line1\n line2",
"handler": "static_response"
}
]
}
]
}
]
}
]
}
}
}
}
}

View File

@ -0,0 +1,9 @@
:80
handle {
respond <<EOF
Hello
# missing EOF marker
}
----------
mismatched leading whitespace in heredoc <<EOF on line #5 [ Hello], expected whitespace [# missing ] to match the closing marker

View File

@ -0,0 +1,9 @@
:80
handle {
respond <<END!
Hello
END!
}
----------
heredoc marker on line #4 must contain only alpha-numeric characters, dashes and underscores; got 'END!'

View File

@ -0,0 +1,10 @@
:80
handle {
respond <<END
line1
line2
END
}
----------
mismatched leading whitespace in heredoc <<END on line #5 [ line1], expected whitespace [ ] to match the closing marker

View File

@ -0,0 +1,9 @@
:80
handle {
respond <<
Hello
END
}
----------
parsing caddyfile tokens for 'handle': unrecognized directive: Hello - are you sure your Caddyfile structure (nesting and braces) is correct?, at Caddyfile:7

View File

@ -0,0 +1,9 @@
:80
handle {
respond <<<END
Hello
END
}
----------
too many '<' for heredoc on line #4; only use two, for example <<END

View File

@ -0,0 +1,12 @@
(import1) {
import import2
}
(import2) {
import import1
}
import import1
----------
a cycle of imports exists between Caddyfile:import2 and Caddyfile:import1

View File

@ -0,0 +1,5 @@
example.com {
invoke foo
}
----------
cannot invoke named route 'foo', which was not defined

View File

@ -0,0 +1,9 @@
@foo {
path /foo
}
handle {
respond "should not work"
}
----------
request matchers may not be defined globally, they must be in a site block; found @foo, at Caddyfile:1

View File

@ -0,0 +1,7 @@
:70000
handle {
respond "should not work"
}
----------
port 70000 is out of range

View File

@ -0,0 +1,7 @@
:-1
handle {
respond "should not work"
}
----------
port -1 is out of range

View File

@ -0,0 +1,7 @@
foo://example.com
handle {
respond "hello"
}
----------
unsupported URL scheme foo://

View File

@ -0,0 +1,7 @@
wss://example.com:70000
handle {
respond "should not work"
}
----------
port 70000 is out of range

View File

@ -0,0 +1,7 @@
wss://example.com
handle {
respond "hello"
}
----------
the scheme wss:// is only supported in browsers; use https:// instead

View File

@ -131,13 +131,7 @@ shadowed.example.com {
{ {
"match": { "match": {
"sni": [ "sni": [
"automated1.example.com" "automated1.example.com",
]
}
},
{
"match": {
"sni": [
"automated2.example.com" "automated2.example.com"
] ]
} }

View File

@ -0,0 +1,87 @@
localhost
respond "hello from localhost"
tls {
client_auth {
mode request
trust_pool inline {
trust_der MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==
}
verifier leaf {
file ../caddy.ca.cer
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "hello from localhost",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"tls_connection_policies": [
{
"match": {
"sni": [
"localhost"
]
},
"client_authentication": {
"ca": {
"provider": "inline",
"trusted_ca_certs": [
"MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ=="
]
},
"verifiers": [
{
"leaf_certs_loaders": [
{
"files": [
"../caddy.ca.cer"
],
"loader": "file"
}
],
"verifier": "leaf"
}
],
"mode": "request"
}
},
{}
]
}
}
}
}
}

View File

@ -0,0 +1,85 @@
localhost
respond "hello from localhost"
tls {
client_auth {
mode request
trust_pool inline {
trust_der MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==
}
verifier leaf file ../caddy.ca.cer
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "hello from localhost",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"tls_connection_policies": [
{
"match": {
"sni": [
"localhost"
]
},
"client_authentication": {
"ca": {
"provider": "inline",
"trusted_ca_certs": [
"MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ=="
]
},
"verifiers": [
{
"leaf_certs_loaders": [
{
"files": [
"../caddy.ca.cer"
],
"loader": "file"
}
],
"verifier": "leaf"
}
],
"mode": "request"
}
},
{}
]
}
}
}
}
}

View File

@ -0,0 +1,94 @@
localhost
respond "hello from localhost"
tls {
client_auth {
mode request
trust_pool inline {
trust_der MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==
}
verifier leaf {
file ../caddy.ca.cer
file ../caddy.ca.cer
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "hello from localhost",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"tls_connection_policies": [
{
"match": {
"sni": [
"localhost"
]
},
"client_authentication": {
"ca": {
"provider": "inline",
"trusted_ca_certs": [
"MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ=="
]
},
"verifiers": [
{
"leaf_certs_loaders": [
{
"files": [
"../caddy.ca.cer"
],
"loader": "file"
},
{
"files": [
"../caddy.ca.cer"
],
"loader": "file"
}
],
"verifier": "leaf"
}
],
"mode": "request"
}
},
{}
]
}
}
}
}
}

View File

@ -0,0 +1,87 @@
localhost
respond "hello from localhost"
tls {
client_auth {
mode request
trust_pool inline {
trust_der MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==
}
verifier leaf {
folder ../
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "hello from localhost",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"tls_connection_policies": [
{
"match": {
"sni": [
"localhost"
]
},
"client_authentication": {
"ca": {
"provider": "inline",
"trusted_ca_certs": [
"MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ=="
]
},
"verifiers": [
{
"leaf_certs_loaders": [
{
"folders": [
"../"
],
"loader": "folder"
}
],
"verifier": "leaf"
}
],
"mode": "request"
}
},
{}
]
}
}
}
}
}

View File

@ -0,0 +1,85 @@
localhost
respond "hello from localhost"
tls {
client_auth {
mode request
trust_pool inline {
trust_der MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==
}
verifier leaf folder ../
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "hello from localhost",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"tls_connection_policies": [
{
"match": {
"sni": [
"localhost"
]
},
"client_authentication": {
"ca": {
"provider": "inline",
"trusted_ca_certs": [
"MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ=="
]
},
"verifiers": [
{
"leaf_certs_loaders": [
{
"folders": [
"../"
],
"loader": "folder"
}
],
"verifier": "leaf"
}
],
"mode": "request"
}
},
{}
]
}
}
}
}
}

View File

@ -0,0 +1,94 @@
localhost
respond "hello from localhost"
tls {
client_auth {
mode request
trust_pool inline {
trust_der MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ==
}
verifier leaf {
folder ../
folder ../
}
}
}
----------
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"localhost"
]
}
],
"handle": [
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"body": "hello from localhost",
"handler": "static_response"
}
]
}
]
}
],
"terminal": true
}
],
"tls_connection_policies": [
{
"match": {
"sni": [
"localhost"
]
},
"client_authentication": {
"ca": {
"provider": "inline",
"trusted_ca_certs": [
"MIIDSzCCAjOgAwIBAgIUfIRObjWNUA4jxQ/0x8BOCvE2Vw4wDQYJKoZIhvcNAQELBQAwFjEUMBIGA1UEAwwLRWFzeS1SU0EgQ0EwHhcNMTkwODI4MTYyNTU5WhcNMjkwODI1MTYyNTU5WjAWMRQwEgYDVQQDDAtFYXN5LVJTQSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK5m5elxhQfMp/3aVJ4JnpN9PUSz6LlP6LePAPFU7gqohVVFVtDkChJAG3FNkNQNlieVTja/bgH9IcC6oKbROwdY1h0MvNV8AHHigvl03WuJD8g2ReVFXXwsnrPmKXCFzQyMI6TYk3m2gYrXsZOU1GLnfMRC3KAMRgE2F45twOs9hqG169YJ6mM2eQjzjCHWI6S2/iUYvYxRkCOlYUbLsMD/AhgAf1plzg6LPqNxtdlwxZnA0ytgkmhK67HtzJu0+ovUCsMv0RwcMhsEo9T8nyFAGt9XLZ63X5WpBCTUApaAUhnG0XnerjmUWb6eUWw4zev54sEfY5F3x002iQaW6cECAwEAAaOBkDCBjTAdBgNVHQ4EFgQU4CBUbZsS2GaNIkGRz/cBsD5ivjswUQYDVR0jBEowSIAU4CBUbZsS2GaNIkGRz/cBsD5ivjuhGqQYMBYxFDASBgNVBAMMC0Vhc3ktUlNBIENBghR8hE5uNY1QDiPFD/THwE4K8TZXDjAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEAKB3V4HIzoiO/Ch6WMj9bLJ2FGbpkMrcb/Eq01hT5zcfKD66lVS1MlK+cRL446Z2b2KDP1oFyVs+qmrmtdwrWgD+nfe2sBmmIHo9m9KygMkEOfG3MghGTEcS+0cTKEcoHYWYyOqQh6jnedXY8Cdm4GM1hAc9MiL3/sqV8YCVSLNnkoNysmr06/rZ0MCUZPGUtRmfd0heWhrfzAKw2HLgX+RAmpOE2MZqWcjvqKGyaRiaZks4nJkP6521aC2Lgp0HhCz1j8/uQ5ldoDszCnu/iro0NAsNtudTMD+YoLQxLqdleIh6CW+illc2VdXwj7mn6J04yns9jfE2jRjW/yTLFuQ=="
]
},
"verifiers": [
{
"leaf_certs_loaders": [
{
"folders": [
"../"
],
"loader": "folder"
},
{
"folders": [
"../"
],
"loader": "folder"
}
],
"verifier": "leaf"
}
],
"mode": "request"
}
},
{}
]
}
}
}
}
}

View File

@ -0,0 +1,9 @@
localhost
tls {
propagation_delay 10s
dns_ttl 5m
}
----------
parsing caddyfile tokens for 'tls': setting DNS challenge options [propagation_delay, dns_ttl] requires a DNS provider (set with the 'dns' subdirective or 'acme_dns' global option), at Caddyfile:6

View File

@ -0,0 +1,7 @@
:443 {
tls {
propagation_timeout 30s
}
}
----------
parsing caddyfile tokens for 'tls': setting DNS challenge options [propagation_timeout] requires a DNS provider (set with the 'dns' subdirective or 'acme_dns' global option), at Caddyfile:4

View File

@ -0,0 +1,7 @@
:443 {
tls {
propagation_delay 30s
}
}
----------
parsing caddyfile tokens for 'tls': setting DNS challenge options [propagation_delay] requires a DNS provider (set with the 'dns' subdirective or 'acme_dns' global option), at Caddyfile:4

View File

@ -2,6 +2,7 @@ localhost
respond "hello from localhost" respond "hello from localhost"
tls { tls {
dns mock
dns_ttl 5m10s dns_ttl 5m10s
} }
---------- ----------
@ -54,6 +55,9 @@ tls {
{ {
"challenges": { "challenges": {
"dns": { "dns": {
"provider": {
"name": "mock"
},
"ttl": 310000000000 "ttl": 310000000000
} }
}, },

View File

@ -2,6 +2,7 @@ localhost
respond "hello from localhost" respond "hello from localhost"
tls { tls {
dns mock
propagation_delay 5m10s propagation_delay 5m10s
propagation_timeout 10m20s propagation_timeout 10m20s
} }
@ -56,7 +57,10 @@ tls {
"challenges": { "challenges": {
"dns": { "dns": {
"propagation_delay": 310000000000, "propagation_delay": 310000000000,
"propagation_timeout": 620000000000 "propagation_timeout": 620000000000,
"provider": {
"name": "mock"
}
} }
}, },
"module": "acme" "module": "acme"

View File

@ -9,8 +9,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddytest" "github.com/caddyserver/caddy/v2/caddytest"
_ "github.com/caddyserver/caddy/v2/internal/testmocks" _ "github.com/caddyserver/caddy/v2/internal/testmocks"
) )
@ -28,30 +28,48 @@ func TestCaddyfileAdaptToJSON(t *testing.T) {
if f.IsDir() { if f.IsDir() {
continue continue
} }
// read the test file
filename := f.Name() filename := f.Name()
data, err := os.ReadFile("./caddyfile_adapt/" + filename)
if err != nil {
t.Errorf("failed to read %s dir: %s", filename, err)
}
// split the Caddyfile (first) and JSON (second) parts // run each file as a subtest, so that we can see which one fails more easily
// (append newline to Caddyfile to match formatter expectations) t.Run(filename, func(t *testing.T) {
parts := strings.Split(string(data), "----------") // read the test file
caddyfile, json := strings.TrimSpace(parts[0])+"\n", strings.TrimSpace(parts[1]) data, err := os.ReadFile("./caddyfile_adapt/" + filename)
if err != nil {
t.Errorf("failed to read %s dir: %s", filename, err)
}
// replace windows newlines in the json with unix newlines // split the Caddyfile (first) and JSON (second) parts
json = winNewlines.ReplaceAllString(json, "\n") // (append newline to Caddyfile to match formatter expectations)
parts := strings.Split(string(data), "----------")
caddyfile, expected := strings.TrimSpace(parts[0])+"\n", strings.TrimSpace(parts[1])
// replace os-specific default path for file_server's hide field // replace windows newlines in the json with unix newlines
replacePath, _ := jsonMod.Marshal(fmt.Sprint(".", string(filepath.Separator), "Caddyfile")) expected = winNewlines.ReplaceAllString(expected, "\n")
json = strings.ReplaceAll(json, `"./Caddyfile"`, string(replacePath))
// run the test // replace os-specific default path for file_server's hide field
ok := caddytest.CompareAdapt(t, filename, caddyfile, "caddyfile", json) replacePath, _ := jsonMod.Marshal(fmt.Sprint(".", string(filepath.Separator), "Caddyfile"))
if !ok { expected = strings.ReplaceAll(expected, `"./Caddyfile"`, string(replacePath))
t.Errorf("failed to adapt %s", filename)
} // if the expected output is JSON, compare it
if len(expected) > 0 && expected[0] == '{' {
ok := caddytest.CompareAdapt(t, filename, caddyfile, "caddyfile", expected)
if !ok {
t.Errorf("failed to adapt %s", filename)
}
return
}
// otherwise, adapt the Caddyfile and check for errors
cfgAdapter := caddyconfig.GetAdapter("caddyfile")
_, _, err = cfgAdapter.Adapt([]byte(caddyfile), nil)
if err == nil {
t.Errorf("expected error for %s but got none", filename)
} else {
normalizedErr := winNewlines.ReplaceAllString(err.Error(), "\n")
if !strings.Contains(normalizedErr, expected) {
t.Errorf("expected error for %s to contain:\n%s\nbut got:\n%s", filename, expected, normalizedErr)
}
}
})
} }
} }

View File

@ -615,7 +615,6 @@ func TestReplaceWithReplacementPlaceholder(t *testing.T) {
respond "{query}"`, "caddyfile") respond "{query}"`, "caddyfile")
tester.AssertGetResponse("http://localhost:9080/endpoint?placeholder=baz&foo=bar", 200, "foo=baz&placeholder=baz") tester.AssertGetResponse("http://localhost:9080/endpoint?placeholder=baz&foo=bar", 200, "foo=baz&placeholder=baz")
} }
func TestReplaceWithKeyPlaceholder(t *testing.T) { func TestReplaceWithKeyPlaceholder(t *testing.T) {
@ -783,6 +782,46 @@ func TestHandleErrorRangeAndCodes(t *testing.T) {
tester.AssertGetResponse("http://localhost:9080/private", 410, "Error in the [400 .. 499] range") tester.AssertGetResponse("http://localhost:9080/private", 410, "Error in the [400 .. 499] range")
} }
func TestHandleErrorSubHandlers(t *testing.T) {
tester := caddytest.NewTester(t)
tester.InitServer(`{
admin localhost:2999
http_port 9080
}
localhost:9080 {
root * /srv
file_server
error /*/internalerr* "Internal Server Error" 500
handle_errors 404 {
handle /en/* {
respond "not found" 404
}
handle /es/* {
respond "no encontrado" 404
}
handle {
respond "default not found"
}
}
handle_errors {
handle {
respond "Default error"
}
handle /en/* {
respond "English error"
}
}
}
`, "caddyfile")
// act and assert
tester.AssertGetResponse("http://localhost:9080/en/notfound", 404, "not found")
tester.AssertGetResponse("http://localhost:9080/es/notfound", 404, "no encontrado")
tester.AssertGetResponse("http://localhost:9080/notfound", 404, "default not found")
tester.AssertGetResponse("http://localhost:9080/es/internalerr", 500, "Default error")
tester.AssertGetResponse("http://localhost:9080/en/internalerr", 500, "English error")
}
func TestInvalidSiteAddressesAsDirectives(t *testing.T) { func TestInvalidSiteAddressesAsDirectives(t *testing.T) {
type testCase struct { type testCase struct {
config, expectedError string config, expectedError string

View File

@ -3,10 +3,11 @@ package integration
import ( import (
"context" "context"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/certmagic" "github.com/caddyserver/certmagic"
"github.com/libdns/libdns" "github.com/libdns/libdns"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
) )
func init() { func init() {
@ -55,7 +56,9 @@ func (MockDNSProvider) SetRecords(ctx context.Context, zone string, recs []libdn
} }
// Interface guard // Interface guard
var _ caddyfile.Unmarshaler = (*MockDNSProvider)(nil) var (
var _ certmagic.DNSProvider = (*MockDNSProvider)(nil) _ caddyfile.Unmarshaler = (*MockDNSProvider)(nil)
var _ caddy.Provisioner = (*MockDNSProvider)(nil) _ certmagic.DNSProvider = (*MockDNSProvider)(nil)
var _ caddy.Module = (*MockDNSProvider)(nil) _ caddy.Provisioner = (*MockDNSProvider)(nil)
_ caddy.Module = (*MockDNSProvider)(nil)
)

View File

@ -13,9 +13,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/caddyserver/caddy/v2/caddytest"
"golang.org/x/net/http2" "golang.org/x/net/http2"
"golang.org/x/net/http2/h2c" "golang.org/x/net/http2/h2c"
"github.com/caddyserver/caddy/v2/caddytest"
) )
// (see https://github.com/caddyserver/caddy/issues/3556 for use case) // (see https://github.com/caddyserver/caddy/issues/3556 for use case)

View File

@ -24,6 +24,7 @@ import (
"io" "io"
"io/fs" "io/fs"
"log" "log"
"maps"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -703,9 +704,7 @@ func AdminAPIRequest(adminAddr, method, uri string, headers http.Header, body io
if body != nil { if body != nil {
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
} }
for k, v := range headers { maps.Copy(req.Header, headers)
req.Header[k] = v
}
// make an HTTP client that dials our network type, since admin // make an HTTP client that dials our network type, since admin
// endpoints aren't always TCP, which is what the default transport // endpoints aren't always TCP, which is what the default transport

View File

@ -20,6 +20,7 @@ import (
"os" "os"
"regexp" "regexp"
"strings" "strings"
"sync"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/cobra/doc" "github.com/spf13/cobra/doc"
@ -80,10 +81,16 @@ type CommandFunc func(Flags) (int, error)
// Commands returns a list of commands initialised by // Commands returns a list of commands initialised by
// RegisterCommand // RegisterCommand
func Commands() map[string]Command { func Commands() map[string]Command {
commandsMu.RLock()
defer commandsMu.RUnlock()
return commands return commands
} }
var commands = make(map[string]Command) var (
commandsMu sync.RWMutex
commands = make(map[string]Command)
)
func init() { func init() {
RegisterCommand(Command{ RegisterCommand(Command{
@ -441,7 +448,7 @@ EXPERIMENTAL: May be changed or removed.
}) })
defaultFactory.Use(func(rootCmd *cobra.Command) { defaultFactory.Use(func(rootCmd *cobra.Command) {
rootCmd.AddCommand(caddyCmdToCobra(Command{ manpageCommand := Command{
Name: "manpage", Name: "manpage",
Usage: "--directory <path>", Usage: "--directory <path>",
Short: "Generates the manual pages for Caddy commands", Short: "Generates the manual pages for Caddy commands",
@ -471,11 +478,12 @@ argument of --directory. If the directory does not exist, it will be created.
return caddy.ExitCodeSuccess, nil return caddy.ExitCodeSuccess, nil
}) })
}, },
})) }
// source: https://github.com/spf13/cobra/blob/main/shell_completions.md // source: https://github.com/spf13/cobra/blob/main/shell_completions.md
rootCmd.AddCommand(&cobra.Command{ completionCommand := Command{
Use: "completion [bash|zsh|fish|powershell]", Name: "completion",
Usage: "[bash|zsh|fish|powershell]",
Short: "Generate completion script", Short: "Generate completion script",
Long: fmt.Sprintf(`To load completions: Long: fmt.Sprintf(`To load completions:
@ -516,24 +524,37 @@ argument of --directory. If the directory does not exist, it will be created.
PS> %[1]s completion powershell > %[1]s.ps1 PS> %[1]s completion powershell > %[1]s.ps1
# and source this file from your PowerShell profile. # and source this file from your PowerShell profile.
`, rootCmd.Root().Name()), `, rootCmd.Root().Name()),
DisableFlagsInUseLine: true, CobraFunc: func(cmd *cobra.Command) {
ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, cmd.DisableFlagsInUseLine = true
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), cmd.ValidArgs = []string{"bash", "zsh", "fish", "powershell"}
RunE: func(cmd *cobra.Command, args []string) error { cmd.Args = cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs)
switch args[0] { cmd.RunE = func(cmd *cobra.Command, args []string) error {
case "bash": switch args[0] {
return cmd.Root().GenBashCompletion(os.Stdout) case "bash":
case "zsh": return cmd.Root().GenBashCompletion(os.Stdout)
return cmd.Root().GenZshCompletion(os.Stdout) case "zsh":
case "fish": return cmd.Root().GenZshCompletion(os.Stdout)
return cmd.Root().GenFishCompletion(os.Stdout, true) case "fish":
case "powershell": return cmd.Root().GenFishCompletion(os.Stdout, true)
return cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) case "powershell":
default: return cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
return fmt.Errorf("unrecognized shell: %s", args[0]) default:
return fmt.Errorf("unrecognized shell: %s", args[0])
}
} }
}, },
}) }
rootCmd.AddCommand(caddyCmdToCobra(manpageCommand))
rootCmd.AddCommand(caddyCmdToCobra(completionCommand))
// add manpage and completion commands to the map of
// available commands, because they're not registered
// through RegisterCommand.
commandsMu.Lock()
commands[manpageCommand.Name] = manpageCommand
commands[completionCommand.Name] = completionCommand
commandsMu.Unlock()
}) })
} }
@ -552,6 +573,9 @@ argument of --directory. If the directory does not exist, it will be created.
// //
// This function should be used in init(). // This function should be used in init().
func RegisterCommand(cmd Command) { func RegisterCommand(cmd Command) {
commandsMu.Lock()
defer commandsMu.Unlock()
if cmd.Name == "" { if cmd.Name == "" {
panic("command name is required") panic("command name is required")
} }
@ -570,6 +594,7 @@ func RegisterCommand(cmd Command) {
defaultFactory.Use(func(rootCmd *cobra.Command) { defaultFactory.Use(func(rootCmd *cobra.Command) {
rootCmd.AddCommand(caddyCmdToCobra(cmd)) rootCmd.AddCommand(caddyCmdToCobra(cmd))
}) })
commands[cmd.Name] = cmd
} }
var commandNameRegex = regexp.MustCompile(`^[a-z0-9]$|^([a-z0-9]+-?[a-z0-9]*)+[a-z0-9]$`) var commandNameRegex = regexp.MustCompile(`^[a-z0-9]$|^([a-z0-9]+-?[a-z0-9]*)+[a-z0-9]$`)

39
cmd/commands_test.go Normal file
View File

@ -0,0 +1,39 @@
package caddycmd
import (
"maps"
"reflect"
"slices"
"testing"
)
func TestCommandsAreAvailable(t *testing.T) {
// trigger init, and build the default factory, so that
// all commands from this package are available
cmd := defaultFactory.Build()
if cmd == nil {
t.Fatal("default factory failed to build")
}
// check that the default factory has 17 commands; it doesn't
// include the commands registered through calls to init in
// other packages
cmds := Commands()
if len(cmds) != 17 {
t.Errorf("expected 17 commands, got %d", len(cmds))
}
commandNames := slices.Collect(maps.Keys(cmds))
slices.Sort(commandNames)
expectedCommandNames := []string{
"adapt", "add-package", "build-info", "completion",
"environ", "fmt", "list-modules", "manpage",
"reload", "remove-package", "run", "start",
"stop", "storage", "upgrade", "validate", "version",
}
if !reflect.DeepEqual(expectedCommandNames, commandNames) {
t.Errorf("expected %v, got %v", expectedCommandNames, commandNames)
}
}

View File

@ -418,7 +418,7 @@ func parseEnvFile(envInput io.Reader) (map[string]string, error) {
// quoted value: support newlines // quoted value: support newlines
if strings.HasPrefix(val, `"`) || strings.HasPrefix(val, "'") { if strings.HasPrefix(val, `"`) || strings.HasPrefix(val, "'") {
quote := string(val[0]) quote := string(val[0])
for !(strings.HasSuffix(line, quote) && !strings.HasSuffix(line, `\`+quote)) { for !strings.HasSuffix(line, quote) || strings.HasSuffix(line, `\`+quote) {
val = strings.ReplaceAll(val, `\`+quote, quote) val = strings.ReplaceAll(val, `\`+quote, quote)
if !scanner.Scan() { if !scanner.Scan() {
break break

View File

@ -235,7 +235,6 @@ func Test_isCaddyfile(t *testing.T) {
wantErr: false, wantErr: false,
}, },
{ {
name: "json is not caddyfile but not error", name: "json is not caddyfile but not error",
args: args{ args: args{
configFile: "./Caddyfile.json", configFile: "./Caddyfile.json",
@ -245,7 +244,6 @@ func Test_isCaddyfile(t *testing.T) {
wantErr: false, wantErr: false,
}, },
{ {
name: "prefix of Caddyfile and ./ with any extension is Caddyfile", name: "prefix of Caddyfile and ./ with any extension is Caddyfile",
args: args{ args: args{
configFile: "./Caddyfile.prd", configFile: "./Caddyfile.prd",
@ -255,7 +253,6 @@ func Test_isCaddyfile(t *testing.T) {
wantErr: false, wantErr: false,
}, },
{ {
name: "prefix of Caddyfile without ./ with any extension is Caddyfile", name: "prefix of Caddyfile without ./ with any extension is Caddyfile",
args: args{ args: args{
configFile: "Caddyfile.prd", configFile: "Caddyfile.prd",

View File

@ -84,7 +84,7 @@ func cmdAddPackage(fl Flags) (int, error) {
return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid module name: %v", err) return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid module name: %v", err)
} }
// only allow a version to be specified if it's different from the existing version // only allow a version to be specified if it's different from the existing version
if _, ok := pluginPkgs[module]; ok && !(version != "" && pluginPkgs[module].Version != version) { if _, ok := pluginPkgs[module]; ok && (version == "" || pluginPkgs[module].Version == version) {
return caddy.ExitCodeFailedStartup, fmt.Errorf("package is already added") return caddy.ExitCodeFailedStartup, fmt.Errorf("package is already added")
} }
pluginPkgs[module] = pluginPackage{Version: version, Path: module} pluginPkgs[module] = pluginPackage{Version: version, Path: module}

View File

@ -91,14 +91,14 @@ func (ctx *Context) OnCancel(f func()) {
ctx.cleanupFuncs = append(ctx.cleanupFuncs, f) ctx.cleanupFuncs = append(ctx.cleanupFuncs, f)
} }
// Filesystems returns a ref to the FilesystemMap. // FileSystems returns a ref to the FilesystemMap.
// EXPERIMENTAL: This API is subject to change. // EXPERIMENTAL: This API is subject to change.
func (ctx *Context) Filesystems() FileSystems { func (ctx *Context) FileSystems() FileSystems {
// if no config is loaded, we use a default filesystemmap, which includes the osfs // if no config is loaded, we use a default filesystemmap, which includes the osfs
if ctx.cfg == nil { if ctx.cfg == nil {
return &filesystems.FilesystemMap{} return &filesystems.FileSystemMap{}
} }
return ctx.cfg.filesystems return ctx.cfg.fileSystems
} }
// Returns the active metrics registry for the context // Returns the active metrics registry for the context
@ -277,6 +277,14 @@ func (ctx Context) LoadModule(structPointer any, fieldName string) (any, error)
return result, nil return result, nil
} }
// emitEvent is a small convenience method so the caddy core can emit events, if the event app is configured.
func (ctx Context) emitEvent(name string, data map[string]any) Event {
if ctx.cfg == nil || ctx.cfg.eventEmitter == nil {
return Event{}
}
return ctx.cfg.eventEmitter.Emit(ctx, name, data)
}
// loadModulesFromSomeMap loads modules from val, which must be a type of map[string]any. // loadModulesFromSomeMap loads modules from val, which must be a type of map[string]any.
// Depending on inlineModuleKey, it will be interpreted as either a ModuleMap (key is the module // Depending on inlineModuleKey, it will be interpreted as either a ModuleMap (key is the module
// name) or as a regular map (key is not the module name, and module name is defined inline). // name) or as a regular map (key is not the module name, and module name is defined inline).
@ -429,6 +437,14 @@ func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (any, error
ctx.moduleInstances[id] = append(ctx.moduleInstances[id], val) ctx.moduleInstances[id] = append(ctx.moduleInstances[id], val)
// if the loaded module happens to be an app that can emit events, store it so the
// core can have access to emit events without an import cycle
if ee, ok := val.(eventEmitter); ok {
if _, ok := ee.(App); ok {
ctx.cfg.eventEmitter = ee
}
}
return val, nil return val, nil
} }
@ -561,11 +577,11 @@ func (ctx Context) Slogger() *slog.Logger {
if err != nil { if err != nil {
panic("config missing, unable to create dev logger: " + err.Error()) panic("config missing, unable to create dev logger: " + err.Error())
} }
return slog.New(zapslog.NewHandler(l.Core(), nil)) return slog.New(zapslog.NewHandler(l.Core()))
} }
mod := ctx.Module() mod := ctx.Module()
if mod == nil { if mod == nil {
return slog.New(zapslog.NewHandler(Log().Core(), nil)) return slog.New(zapslog.NewHandler(Log().Core()))
} }
return slog.New(zapslog.NewHandler(ctx.cfg.Logging.Logger(mod).Core(), return slog.New(zapslog.NewHandler(ctx.cfg.Logging.Logger(mod).Core(),
zapslog.WithName(string(mod.CaddyModule().ID)), zapslog.WithName(string(mod.CaddyModule().ID)),
@ -600,3 +616,11 @@ func (ctx *Context) WithValue(key, value any) Context {
exitFuncs: ctx.exitFuncs, exitFuncs: ctx.exitFuncs,
} }
} }
// eventEmitter is a small interface that inverts dependencies for
// the caddyevents package, so the core can emit events without an
// import cycle (i.e. the caddy package doesn't have to import
// the caddyevents package, which imports the caddy package).
type eventEmitter interface {
Emit(ctx Context, eventName string, data map[string]any) Event
}

15
go.mod
View File

@ -8,18 +8,18 @@ require (
github.com/Masterminds/sprig/v3 v3.3.0 github.com/Masterminds/sprig/v3 v3.3.0
github.com/alecthomas/chroma/v2 v2.15.0 github.com/alecthomas/chroma/v2 v2.15.0
github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b
github.com/caddyserver/certmagic v0.22.1 github.com/caddyserver/certmagic v0.23.0
github.com/caddyserver/zerossl v0.1.3 github.com/caddyserver/zerossl v0.1.3
github.com/cloudflare/circl v1.6.0 github.com/cloudflare/circl v1.6.1
github.com/dustin/go-humanize v1.0.1 github.com/dustin/go-humanize v1.0.1
github.com/go-chi/chi/v5 v5.2.1 github.com/go-chi/chi/v5 v5.2.1
github.com/google/cel-go v0.24.1 github.com/google/cel-go v0.24.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/klauspost/compress v1.18.0 github.com/klauspost/compress v1.18.0
github.com/klauspost/cpuid/v2 v2.2.10 github.com/klauspost/cpuid/v2 v2.2.10
github.com/mholt/acmez/v3 v3.1.1 github.com/mholt/acmez/v3 v3.1.2
github.com/prometheus/client_golang v1.19.1 github.com/prometheus/client_golang v1.19.1
github.com/quic-go/quic-go v0.50.1 github.com/quic-go/quic-go v0.53.0
github.com/smallstep/certificates v0.26.1 github.com/smallstep/certificates v0.26.1
github.com/smallstep/nosql v0.6.1 github.com/smallstep/nosql v0.6.1
github.com/smallstep/truststore v0.13.0 github.com/smallstep/truststore v0.13.0
@ -39,7 +39,7 @@ require (
go.uber.org/zap/exp v0.3.0 go.uber.org/zap/exp v0.3.0
golang.org/x/crypto v0.36.0 golang.org/x/crypto v0.36.0
golang.org/x/crypto/x509roots/fallback v0.0.0-20250305170421-49bf5b80c810 golang.org/x/crypto/x509roots/fallback v0.0.0-20250305170421-49bf5b80c810
golang.org/x/net v0.37.0 golang.org/x/net v0.38.0
golang.org/x/sync v0.12.0 golang.org/x/sync v0.12.0
golang.org/x/term v0.30.0 golang.org/x/term v0.30.0
golang.org/x/time v0.11.0 golang.org/x/time v0.11.0
@ -60,9 +60,7 @@ require (
github.com/google/certificate-transparency-go v1.1.8-0.20240110162603-74a5dd331745 // indirect github.com/google/certificate-transparency-go v1.1.8-0.20240110162603-74a5dd331745 // indirect
github.com/google/go-tpm v0.9.0 // indirect github.com/google/go-tpm v0.9.0 // indirect
github.com/google/go-tspi v0.3.0 // indirect github.com/google/go-tspi v0.3.0 // indirect
github.com/google/pprof v0.0.0-20231212022811-ec68065c825e // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 // indirect
github.com/onsi/ginkgo/v2 v2.13.2 // indirect
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/quic-go/qpack v0.5.1 // indirect github.com/quic-go/qpack v0.5.1 // indirect
@ -103,7 +101,6 @@ require (
github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-sql-driver/mysql v1.7.1 // indirect github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/golang/protobuf v1.5.4 // indirect github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect github.com/golang/snappy v0.0.4 // indirect
github.com/huandu/xstrings v1.5.0 // indirect github.com/huandu/xstrings v1.5.0 // indirect
@ -116,7 +113,7 @@ require (
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgtype v1.14.0 // indirect github.com/jackc/pgtype v1.14.0 // indirect
github.com/jackc/pgx/v4 v4.18.3 // indirect github.com/jackc/pgx/v4 v4.18.3 // indirect
github.com/libdns/libdns v0.2.3 github.com/libdns/libdns v1.0.0-beta.1
github.com/manifoldco/promptui v0.9.0 // indirect github.com/manifoldco/promptui v0.9.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect

33
go.sum
View File

@ -93,8 +93,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s=
github.com/caddyserver/certmagic v0.22.1 h1:FTI1H+N7UrVWx1mVW7Am0JrOtTNgJO/uOsIhjtDZM60= github.com/caddyserver/certmagic v0.23.0 h1:CfpZ/50jMfG4+1J/u2LV6piJq4HOfO6ppOnOf7DkFEU=
github.com/caddyserver/certmagic v0.22.1/go.mod h1:hbqE7BnkjhX5IJiFslPmrSeobSeZvI6ux8tyxhsd6qs= github.com/caddyserver/certmagic v0.23.0/go.mod h1:9mEZIWqqWoI+Gf+4Trh04MOVPD0tGSxtqsxg87hAIH4=
github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA= github.com/caddyserver/zerossl v0.1.3 h1:onS+pxp3M8HnHpN5MMbOMyNjmTheJyWRaZYwn+YTAyA=
github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4= github.com/caddyserver/zerossl v0.1.3/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
@ -113,8 +113,8 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMn
github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04=
github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/circl v1.6.0 h1:cr5JKic4HI+LkINy2lg3W2jF8sHCVTBncJr5gIIq7qk= github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
github.com/cloudflare/circl v1.6.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs= github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I= github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
@ -185,8 +185,6 @@ github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrt
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-stack/stack v1.6.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.6.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw= github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
@ -225,8 +223,6 @@ github.com/google/go-tspi v0.3.0 h1:ADtq8RKfP+jrTyIWIZDIYcKOMecRqNJFOew2IT0Inus=
github.com/google/go-tspi v0.3.0/go.mod h1:xfMGI3G0PhxCdNVcYr1C4C+EizojDg/TXuX5by8CiHI= github.com/google/go-tspi v0.3.0/go.mod h1:xfMGI3G0PhxCdNVcYr1C4C+EizojDg/TXuX5by8CiHI=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20231212022811-ec68065c825e h1:bwOy7hAFd0C91URzMIEBfr6BAz29yk7Qj0cy6S7DJlU=
github.com/google/pprof v0.0.0-20231212022811-ec68065c825e/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
@ -327,8 +323,8 @@ github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/libdns/libdns v0.2.3 h1:ba30K4ObwMGB/QTmqUxf3H4/GmUrCAIkMWejeGl12v8= github.com/libdns/libdns v1.0.0-beta.1 h1:KIf4wLfsrEpXpZ3vmc/poM8zCATXT2klbdPe6hyOBjQ=
github.com/libdns/libdns v0.2.3/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= github.com/libdns/libdns v1.0.0-beta.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
@ -347,8 +343,8 @@ github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mholt/acmez/v3 v3.1.1 h1:Jh+9uKHkPxUJdxM16q5mOr+G2V0aqkuFtNA28ihCxhQ= github.com/mholt/acmez/v3 v3.1.2 h1:auob8J/0FhmdClQicvJvuDavgd5ezwLBfKuYmynhYzc=
github.com/mholt/acmez/v3 v3.1.1/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ= github.com/mholt/acmez/v3 v3.1.2/go.mod h1:L1wOU06KKvq7tswuMDwKdcHeKpFFgkppZy/y0DFxagQ=
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY= github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY=
github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs= github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs=
@ -364,10 +360,6 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo= github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM= github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=
github.com/onsi/ginkgo/v2 v2.13.2 h1:Bi2gGVkfn6gQcjNjZJVO8Gf0FHzMPf2phUei9tejVMs=
github.com/onsi/ginkgo/v2 v2.13.2/go.mod h1:XStQ8QcGwLyF4HdfcZB8SFOS/MWCgDuXMSBe6zrvLgM=
github.com/onsi/gomega v1.29.0 h1:KIA/t2t5UBzoirT4H9tsML45GEbo3ouUnBHsCfD2tVg=
github.com/onsi/gomega v1.29.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ=
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8= github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y= github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
@ -397,8 +389,8 @@ github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo= github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.50.1 h1:unsgjFIUqW8a2oopkY7YNONpV1gYND6Nt9hnt1PN94Q= github.com/quic-go/quic-go v0.53.0 h1:QHX46sISpG2S03dPeZBgVIZp8dGagIaiu2FiVYvpCZI=
github.com/quic-go/quic-go v0.50.1/go.mod h1:Vim6OmUvlYdwBhXP9ZVrtGmCMWa3wEqhq3NgYrI8b4E= github.com/quic-go/quic-go v0.53.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
@ -491,7 +483,6 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
@ -633,8 +624,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=

View File

@ -7,10 +7,10 @@ import (
) )
const ( const (
DefaultFilesystemKey = "default" DefaultFileSystemKey = "default"
) )
var DefaultFilesystem = &wrapperFs{key: DefaultFilesystemKey, FS: OsFS{}} var DefaultFileSystem = &wrapperFs{key: DefaultFileSystemKey, FS: OsFS{}}
// wrapperFs exists so can easily add to wrapperFs down the line // wrapperFs exists so can easily add to wrapperFs down the line
type wrapperFs struct { type wrapperFs struct {
@ -18,24 +18,24 @@ type wrapperFs struct {
fs.FS fs.FS
} }
// FilesystemMap stores a map of filesystems // FileSystemMap stores a map of filesystems
// the empty key will be overwritten to be the default key // the empty key will be overwritten to be the default key
// it includes a default filesystem, based off the os fs // it includes a default filesystem, based off the os fs
type FilesystemMap struct { type FileSystemMap struct {
m sync.Map m sync.Map
} }
// note that the first invocation of key cannot be called in a racy context. // note that the first invocation of key cannot be called in a racy context.
func (f *FilesystemMap) key(k string) string { func (f *FileSystemMap) key(k string) string {
if k == "" { if k == "" {
k = DefaultFilesystemKey k = DefaultFileSystemKey
} }
return k return k
} }
// Register will add the filesystem with key to later be retrieved // Register will add the filesystem with key to later be retrieved
// A call with a nil fs will call unregister, ensuring that a call to Default() will never be nil // A call with a nil fs will call unregister, ensuring that a call to Default() will never be nil
func (f *FilesystemMap) Register(k string, v fs.FS) { func (f *FileSystemMap) Register(k string, v fs.FS) {
k = f.key(k) k = f.key(k)
if v == nil { if v == nil {
f.Unregister(k) f.Unregister(k)
@ -47,23 +47,23 @@ func (f *FilesystemMap) Register(k string, v fs.FS) {
// Unregister will remove the filesystem with key from the filesystem map // Unregister will remove the filesystem with key from the filesystem map
// if the key is the default key, it will set the default to the osFS instead of deleting it // if the key is the default key, it will set the default to the osFS instead of deleting it
// modules should call this on cleanup to be safe // modules should call this on cleanup to be safe
func (f *FilesystemMap) Unregister(k string) { func (f *FileSystemMap) Unregister(k string) {
k = f.key(k) k = f.key(k)
if k == DefaultFilesystemKey { if k == DefaultFileSystemKey {
f.m.Store(k, DefaultFilesystem) f.m.Store(k, DefaultFileSystem)
} else { } else {
f.m.Delete(k) f.m.Delete(k)
} }
} }
// Get will get a filesystem with a given key // Get will get a filesystem with a given key
func (f *FilesystemMap) Get(k string) (v fs.FS, ok bool) { func (f *FileSystemMap) Get(k string) (v fs.FS, ok bool) {
k = f.key(k) k = f.key(k)
c, ok := f.m.Load(strings.TrimSpace(k)) c, ok := f.m.Load(strings.TrimSpace(k))
if !ok { if !ok {
if k == DefaultFilesystemKey { if k == DefaultFileSystemKey {
f.m.Store(k, DefaultFilesystem) f.m.Store(k, DefaultFileSystem)
return DefaultFilesystem, true return DefaultFileSystem, true
} }
return nil, ok return nil, ok
} }
@ -71,7 +71,7 @@ func (f *FilesystemMap) Get(k string) (v fs.FS, ok bool) {
} }
// Default will get the default filesystem in the filesystem map // Default will get the default filesystem in the filesystem map
func (f *FilesystemMap) Default() fs.FS { func (f *FileSystemMap) Default() fs.FS {
val, _ := f.Get(DefaultFilesystemKey) val, _ := f.Get(DefaultFileSystemKey)
return val return val
} }

22
internal/logs.go Normal file
View File

@ -0,0 +1,22 @@
package internal
import "fmt"
// MaxSizeSubjectsListForLog returns the keys in the map as a slice of maximum length
// maxToDisplay. It is useful for logging domains being managed, for example, since a
// map is typically needed for quick lookup, but a slice is needed for logging, and this
// can be quite a doozy since there may be a huge amount (hundreds of thousands).
func MaxSizeSubjectsListForLog(subjects map[string]struct{}, maxToDisplay int) []string {
numberOfNamesToDisplay := min(len(subjects), maxToDisplay)
domainsToDisplay := make([]string, 0, numberOfNamesToDisplay)
for domain := range subjects {
domainsToDisplay = append(domainsToDisplay, domain)
if len(domainsToDisplay) >= numberOfNamesToDisplay {
break
}
}
if len(subjects) > maxToDisplay {
domainsToDisplay = append(domainsToDisplay, fmt.Sprintf("(and %d more...)", len(subjects)-maxToDisplay))
}
return domainsToDisplay
}

View File

@ -210,7 +210,7 @@ func (na NetworkAddress) IsUnixNetwork() bool {
return IsUnixNetwork(na.Network) return IsUnixNetwork(na.Network)
} }
// IsUnixNetwork returns true if na.Network is // IsFdNetwork returns true if na.Network is
// fd or fdgram. // fd or fdgram.
func (na NetworkAddress) IsFdNetwork() bool { func (na NetworkAddress) IsFdNetwork() bool {
return IsFdNetwork(na.Network) return IsFdNetwork(na.Network)
@ -430,7 +430,7 @@ func JoinNetworkAddress(network, host, port string) string {
// address instead. // address instead.
// //
// NOTE: This API is EXPERIMENTAL and may be changed or removed. // NOTE: This API is EXPERIMENTAL and may be changed or removed.
func (na NetworkAddress) ListenQUIC(ctx context.Context, portOffset uint, config net.ListenConfig, tlsConf *tls.Config) (http3.QUICEarlyListener, error) { func (na NetworkAddress) ListenQUIC(ctx context.Context, portOffset uint, config net.ListenConfig, tlsConf *tls.Config) (http3.QUICListener, error) {
lnKey := listenerKey("quic"+na.Network, na.JoinHostPort(portOffset)) lnKey := listenerKey("quic"+na.Network, na.JoinHostPort(portOffset))
sharedEarlyListener, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) { sharedEarlyListener, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) {
@ -610,7 +610,7 @@ type fakeCloseQuicListener struct {
// server on which Accept would be called with non-empty contexts // server on which Accept would be called with non-empty contexts
// (mind that the default net listeners' Accept doesn't take a context argument) // (mind that the default net listeners' Accept doesn't take a context argument)
// sounds way too rare for us to sacrifice efficiency here. // sounds way too rare for us to sacrifice efficiency here.
func (fcql *fakeCloseQuicListener) Accept(_ context.Context) (quic.EarlyConnection, error) { func (fcql *fakeCloseQuicListener) Accept(_ context.Context) (*quic.Conn, error) {
conn, err := fcql.sharedQuicListener.Accept(fcql.context) conn, err := fcql.sharedQuicListener.Accept(fcql.context)
if err == nil { if err == nil {
return conn, nil return conn, nil
@ -641,7 +641,7 @@ func RegisterNetwork(network string, getListener ListenerFunc) {
if network == "tcp" || network == "tcp4" || network == "tcp6" || if network == "tcp" || network == "tcp4" || network == "tcp6" ||
network == "udp" || network == "udp4" || network == "udp6" || network == "udp" || network == "udp4" || network == "udp6" ||
network == "unix" || network == "unixpacket" || network == "unixgram" || network == "unix" || network == "unixpacket" || network == "unixgram" ||
strings.HasPrefix("ip:", network) || strings.HasPrefix("ip4:", network) || strings.HasPrefix("ip6:", network) || strings.HasPrefix(network, "ip:") || strings.HasPrefix(network, "ip4:") || strings.HasPrefix(network, "ip6:") ||
network == "fd" || network == "fdgram" { network == "fd" || network == "fdgram" {
panic("network type " + network + " is reserved") panic("network type " + network + " is reserved")
} }

View File

@ -30,7 +30,7 @@ func TestSplitNetworkAddress(t *testing.T) {
expectErr bool expectErr bool
}{ }{
{ {
input: "", input: "",
expectHost: "", expectHost: "",
}, },
{ {
@ -41,7 +41,7 @@ func TestSplitNetworkAddress(t *testing.T) {
input: ":", // empty host & empty port input: ":", // empty host & empty port
}, },
{ {
input: "::", input: "::",
expectHost: "::", expectHost: "::",
}, },
{ {
@ -184,9 +184,8 @@ func TestParseNetworkAddress(t *testing.T) {
expectErr bool expectErr bool
}{ }{
{ {
input: "", input: "",
expectAddr: NetworkAddress{ expectAddr: NetworkAddress{},
},
}, },
{ {
input: ":", input: ":",
@ -311,9 +310,8 @@ func TestParseNetworkAddressWithDefaults(t *testing.T) {
expectErr bool expectErr bool
}{ }{
{ {
input: "", input: "",
expectAddr: NetworkAddress{ expectAddr: NetworkAddress{},
},
}, },
{ {
input: ":", input: ":",

View File

@ -20,6 +20,7 @@ import (
"io" "io"
"log" "log"
"os" "os"
"slices"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -161,7 +162,9 @@ func (logging *Logging) setupNewDefault(ctx Context) error {
if err != nil { if err != nil {
return fmt.Errorf("setting up default log: %v", err) return fmt.Errorf("setting up default log: %v", err)
} }
newDefault.logger = zap.New(newDefault.CustomLog.core, options...)
filteringCore := &filteringCore{newDefault.CustomLog.core, newDefault.CustomLog}
newDefault.logger = zap.New(filteringCore, options...)
// redirect the default caddy logs // redirect the default caddy logs
defaultLoggerMu.Lock() defaultLoggerMu.Lock()
@ -490,10 +493,8 @@ func (cl *CustomLog) provision(ctx Context, logging *Logging) error {
if len(cl.Include) > 0 && len(cl.Exclude) > 0 { if len(cl.Include) > 0 && len(cl.Exclude) > 0 {
// prevent intersections // prevent intersections
for _, allow := range cl.Include { for _, allow := range cl.Include {
for _, deny := range cl.Exclude { if slices.Contains(cl.Exclude, allow) {
if allow == deny { return fmt.Errorf("include and exclude must not intersect, but found %s in both lists", allow)
return fmt.Errorf("include and exclude must not intersect, but found %s in both lists", allow)
}
} }
} }

106
logging_test.go Normal file
View File

@ -0,0 +1,106 @@
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package caddy
import "testing"
func TestCustomLog_loggerAllowed(t *testing.T) {
type fields struct {
BaseLog BaseLog
Include []string
Exclude []string
}
type args struct {
name string
isModule bool
}
tests := []struct {
name string
fields fields
args args
want bool
}{
{
name: "include",
fields: fields{
Include: []string{"foo"},
},
args: args{
name: "foo",
isModule: true,
},
want: true,
},
{
name: "exclude",
fields: fields{
Exclude: []string{"foo"},
},
args: args{
name: "foo",
isModule: true,
},
want: false,
},
{
name: "include and exclude",
fields: fields{
Include: []string{"foo"},
Exclude: []string{"foo"},
},
args: args{
name: "foo",
isModule: true,
},
want: false,
},
{
name: "include and exclude (longer namespace)",
fields: fields{
Include: []string{"foo.bar"},
Exclude: []string{"foo"},
},
args: args{
name: "foo.bar",
isModule: true,
},
want: true,
},
{
name: "excluded module is not printed",
fields: fields{
Include: []string{"admin.api.load"},
Exclude: []string{"admin.api"},
},
args: args{
name: "admin.api",
isModule: false,
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cl := &CustomLog{
BaseLog: tt.fields.BaseLog,
Include: tt.fields.Include,
Exclude: tt.fields.Exclude,
}
if got := cl.loggerAllowed(tt.args.name, tt.args.isModule); got != tt.want {
t.Errorf("CustomLog.loggerAllowed() = %v, want %v", got, tt.want)
}
})
}
}

View File

@ -20,9 +20,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"time"
"github.com/google/uuid"
"go.uber.org/zap" "go.uber.org/zap"
"github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2"
@ -206,27 +204,26 @@ func (app *App) On(eventName string, handler Handler) error {
// //
// Note that the data map is not copied, for efficiency. After Emit() is called, the // Note that the data map is not copied, for efficiency. After Emit() is called, the
// data passed in should not be changed in other goroutines. // data passed in should not be changed in other goroutines.
func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) Event { func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) caddy.Event {
logger := app.logger.With(zap.String("name", eventName)) logger := app.logger.With(zap.String("name", eventName))
id, err := uuid.NewRandom() e, err := caddy.NewEvent(ctx, eventName, data)
if err != nil { if err != nil {
logger.Error("failed generating new event ID", zap.Error(err)) logger.Error("failed to create event", zap.Error(err))
} }
eventName = strings.ToLower(eventName) var originModule caddy.ModuleInfo
var originModuleID caddy.ModuleID
e := Event{ var originModuleName string
Data: data, if origin := e.Origin(); origin != nil {
id: id, originModule = origin.CaddyModule()
ts: time.Now(), originModuleID = originModule.ID
name: eventName, originModuleName = originModule.String()
origin: ctx.Module(),
} }
logger = logger.With( logger = logger.With(
zap.String("id", e.id.String()), zap.String("id", e.ID().String()),
zap.String("origin", e.origin.CaddyModule().String())) zap.String("origin", originModuleName))
// add event info to replacer, make sure it's in the context // add event info to replacer, make sure it's in the context
repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
@ -239,21 +236,21 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
case "event": case "event":
return e, true return e, true
case "event.id": case "event.id":
return e.id, true return e.ID(), true
case "event.name": case "event.name":
return e.name, true return e.Name(), true
case "event.time": case "event.time":
return e.ts, true return e.Timestamp(), true
case "event.time_unix": case "event.time_unix":
return e.ts.UnixMilli(), true return e.Timestamp().UnixMilli(), true
case "event.module": case "event.module":
return e.origin.CaddyModule().ID, true return originModuleID, true
case "event.data": case "event.data":
return e.Data, true return e.Data, true
} }
if strings.HasPrefix(key, "event.data.") { if after, ok0 := strings.CutPrefix(key, "event.data."); ok0 {
key = strings.TrimPrefix(key, "event.data.") key = after
if val, ok := e.Data[key]; ok { if val, ok := e.Data[key]; ok {
return val, true return val, true
} }
@ -269,7 +266,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
// invoke handlers bound to the event by name and also all events; this for loop // invoke handlers bound to the event by name and also all events; this for loop
// iterates twice at most: once for the event name, once for "" (all events) // iterates twice at most: once for the event name, once for "" (all events)
for { for {
moduleID := e.origin.CaddyModule().ID moduleID := originModuleID
// implement propagation up the module tree (i.e. start with "a.b.c" then "a.b" then "a" then "") // implement propagation up the module tree (i.e. start with "a.b.c" then "a.b" then "a" then "")
for { for {
@ -292,7 +289,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
zap.Any("handler", handler)) zap.Any("handler", handler))
if err := handler.Handle(ctx, e); err != nil { if err := handler.Handle(ctx, e); err != nil {
aborted := errors.Is(err, ErrAborted) aborted := errors.Is(err, caddy.ErrEventAborted)
logger.Error("handler error", logger.Error("handler error",
zap.Error(err), zap.Error(err),
@ -326,76 +323,9 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
return e return e
} }
// Event represents something that has happened or is happening.
// An Event value is not synchronized, so it should be copied if
// being used in goroutines.
//
// EXPERIMENTAL: As with the rest of this package, events are
// subject to change.
type Event struct {
// If non-nil, the event has been aborted, meaning
// propagation has stopped to other handlers and
// the code should stop what it was doing. Emitters
// may choose to use this as a signal to adjust their
// code path appropriately.
Aborted error
// The data associated with the event. Usually the
// original emitter will be the only one to set or
// change these values, but the field is exported
// so handlers can have full access if needed.
// However, this map is not synchronized, so
// handlers must not use this map directly in new
// goroutines; instead, copy the map to use it in a
// goroutine.
Data map[string]any
id uuid.UUID
ts time.Time
name string
origin caddy.Module
}
func (e Event) ID() uuid.UUID { return e.id }
func (e Event) Timestamp() time.Time { return e.ts }
func (e Event) Name() string { return e.name }
func (e Event) Origin() caddy.Module { return e.origin }
// CloudEvent exports event e as a structure that, when
// serialized as JSON, is compatible with the
// CloudEvents spec.
func (e Event) CloudEvent() CloudEvent {
dataJSON, _ := json.Marshal(e.Data)
return CloudEvent{
ID: e.id.String(),
Source: e.origin.CaddyModule().String(),
SpecVersion: "1.0",
Type: e.name,
Time: e.ts,
DataContentType: "application/json",
Data: dataJSON,
}
}
// CloudEvent is a JSON-serializable structure that
// is compatible with the CloudEvents specification.
// See https://cloudevents.io.
type CloudEvent struct {
ID string `json:"id"`
Source string `json:"source"`
SpecVersion string `json:"specversion"`
Type string `json:"type"`
Time time.Time `json:"time"`
DataContentType string `json:"datacontenttype,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
// ErrAborted cancels an event.
var ErrAborted = errors.New("event aborted")
// Handler is a type that can handle events. // Handler is a type that can handle events.
type Handler interface { type Handler interface {
Handle(context.Context, Event) error Handle(context.Context, caddy.Event) error
} }
// Interface guards // Interface guards

View File

@ -69,11 +69,11 @@ func (xs *Filesystems) Provision(ctx caddy.Context) error {
} }
// register that module // register that module
ctx.Logger().Debug("registering fs", zap.String("fs", f.Key)) ctx.Logger().Debug("registering fs", zap.String("fs", f.Key))
ctx.Filesystems().Register(f.Key, f.fileSystem) ctx.FileSystems().Register(f.Key, f.fileSystem)
// remember to unregister the module when we are done // remember to unregister the module when we are done
xs.defers = append(xs.defers, func() { xs.defers = append(xs.defers, func() {
ctx.Logger().Debug("unregistering fs", zap.String("fs", f.Key)) ctx.Logger().Debug("unregistering fs", zap.String("fs", f.Key))
ctx.Filesystems().Unregister(f.Key) ctx.FileSystems().Unregister(f.Key)
}) })
} }
return nil return nil

View File

@ -73,7 +73,7 @@ func init() {
// `{http.request.local.host}` | The host (IP) part of the local address the connection arrived on // `{http.request.local.host}` | The host (IP) part of the local address the connection arrived on
// `{http.request.local.port}` | The port part of the local address the connection arrived on // `{http.request.local.port}` | The port part of the local address the connection arrived on
// `{http.request.local}` | The local address the connection arrived on // `{http.request.local}` | The local address the connection arrived on
// `{http.request.remote.host}` | The host (IP) part of the remote client's address // `{http.request.remote.host}` | The host (IP) part of the remote client's address, if available (not known with HTTP/3 early data)
// `{http.request.remote.port}` | The port part of the remote client's address // `{http.request.remote.port}` | The port part of the remote client's address
// `{http.request.remote}` | The address of the remote client // `{http.request.remote}` | The address of the remote client
// `{http.request.scheme}` | The request scheme, typically `http` or `https` // `{http.request.scheme}` | The request scheme, typically `http` or `https`
@ -152,7 +152,7 @@ type App struct {
tlsApp *caddytls.TLS tlsApp *caddytls.TLS
// used temporarily between phases 1 and 2 of auto HTTPS // used temporarily between phases 1 and 2 of auto HTTPS
allCertDomains []string allCertDomains map[string]struct{}
} }
// CaddyModule returns the Caddy module information. // CaddyModule returns the Caddy module information.

View File

@ -25,6 +25,7 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
"github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/internal"
"github.com/caddyserver/caddy/v2/modules/caddytls" "github.com/caddyserver/caddy/v2/modules/caddytls"
) )
@ -65,12 +66,6 @@ type AutoHTTPSConfig struct {
// enabled. To force automated certificate management // enabled. To force automated certificate management
// regardless of loaded certificates, set this to true. // regardless of loaded certificates, set this to true.
IgnoreLoadedCerts bool `json:"ignore_loaded_certificates,omitempty"` IgnoreLoadedCerts bool `json:"ignore_loaded_certificates,omitempty"`
// If true, automatic HTTPS will prefer wildcard names
// and ignore non-wildcard names if both are available.
// This allows for writing a config with top-level host
// matchers without having those names produce certificates.
PreferWildcard bool `json:"prefer_wildcard,omitempty"`
} }
// automaticHTTPSPhase1 provisions all route matchers, determines // automaticHTTPSPhase1 provisions all route matchers, determines
@ -163,33 +158,8 @@ func (app *App) automaticHTTPSPhase1(ctx caddy.Context, repl *caddy.Replacer) er
} }
} }
// trim the list of domains covered by wildcards, if configured
if srv.AutoHTTPS.PreferWildcard {
wildcards := make(map[string]struct{})
for d := range serverDomainSet {
if strings.HasPrefix(d, "*.") {
wildcards[d[2:]] = struct{}{}
}
}
for d := range serverDomainSet {
if strings.HasPrefix(d, "*.") {
continue
}
base := d
if idx := strings.Index(d, "."); idx != -1 {
base = d[idx+1:]
}
if _, ok := wildcards[base]; ok {
delete(serverDomainSet, d)
}
}
}
// build the list of domains that could be used with ECH (if enabled) // build the list of domains that could be used with ECH (if enabled)
// so the TLS app can know to publish ECH configs for them; we do this // so the TLS app can know to publish ECH configs for them
// after trimming domains covered by wildcards because, presumably,
// if the user wants to use wildcard certs, they also want to use the
// wildcard for ECH, rather than individual subdomains
echDomains := make([]string, 0, len(serverDomainSet)) echDomains := make([]string, 0, len(serverDomainSet))
for d := range serverDomainSet { for d := range serverDomainSet {
echDomains = append(echDomains, d) echDomains = append(echDomains, d)
@ -295,19 +265,10 @@ func (app *App) automaticHTTPSPhase1(ctx caddy.Context, repl *caddy.Replacer) er
} }
} }
// we now have a list of all the unique names for which we need certs; // we now have a list of all the unique names for which we need certs
// turn the set into a slice so that phase 2 can use it
app.allCertDomains = make([]string, 0, len(uniqueDomainsForCerts))
var internal, tailscale []string var internal, tailscale []string
uniqueDomainsLoop: uniqueDomainsLoop:
for d := range uniqueDomainsForCerts { for d := range uniqueDomainsForCerts {
if !isTailscaleDomain(d) {
// whether or not there is already an automation policy for this
// name, we should add it to the list to manage a cert for it,
// unless it's a Tailscale domain, because we don't manage those
app.allCertDomains = append(app.allCertDomains, d)
}
// some names we've found might already have automation policies // some names we've found might already have automation policies
// explicitly specified for them; we should exclude those from // explicitly specified for them; we should exclude those from
// our hidden/implicit policy, since applying a name to more than // our hidden/implicit policy, since applying a name to more than
@ -346,6 +307,7 @@ uniqueDomainsLoop:
} }
if isTailscaleDomain(d) { if isTailscaleDomain(d) {
tailscale = append(tailscale, d) tailscale = append(tailscale, d)
delete(uniqueDomainsForCerts, d) // not managed by us; handled separately
} else if shouldUseInternal(d) { } else if shouldUseInternal(d) {
internal = append(internal, d) internal = append(internal, d)
} }
@ -381,7 +343,7 @@ uniqueDomainsLoop:
// match on known domain names, unless it's our special case of a // match on known domain names, unless it's our special case of a
// catch-all which is an empty string (common among catch-all sites // catch-all which is an empty string (common among catch-all sites
// that enable on-demand TLS for yet-unknown domain names) // that enable on-demand TLS for yet-unknown domain names)
if !(len(domains) == 1 && domains[0] == "") { if len(domains) != 1 || domains[0] != "" {
matcherSet = append(matcherSet, MatchHost(domains)) matcherSet = append(matcherSet, MatchHost(domains))
} }
@ -475,6 +437,9 @@ redirServersLoop:
} }
} }
// persist the domains/IPs we're managing certs for through provisioning/startup
app.allCertDomains = uniqueDomainsForCerts
logger.Debug("adjusted config", logger.Debug("adjusted config",
zap.Reflect("tls", app.tlsApp), zap.Reflect("tls", app.tlsApp),
zap.Reflect("http", app)) zap.Reflect("http", app))
@ -777,7 +742,7 @@ func (app *App) automaticHTTPSPhase2() error {
return nil return nil
} }
app.logger.Info("enabling automatic TLS certificate management", app.logger.Info("enabling automatic TLS certificate management",
zap.Strings("domains", app.allCertDomains), zap.Strings("domains", internal.MaxSizeSubjectsListForLog(app.allCertDomains, 1000)),
) )
err := app.tlsApp.Manage(app.allCertDomains) err := app.tlsApp.Manage(app.allCertDomains)
if err != nil { if err != nil {

View File

@ -236,10 +236,7 @@ func (c *Cache) makeRoom() {
// the cache is on a long tail, we can save a lot of CPU // the cache is on a long tail, we can save a lot of CPU
// time by doing a whole bunch of deletions now and then // time by doing a whole bunch of deletions now and then
// we won't have to do them again for a while // we won't have to do them again for a while
numToDelete := len(c.cache) / 10 numToDelete := max(len(c.cache)/10, 1)
if numToDelete < 1 {
numToDelete = 1
}
for deleted := 0; deleted <= numToDelete; deleted++ { for deleted := 0; deleted <= numToDelete; deleted++ {
// Go maps are "nondeterministic" not actually random, // Go maps are "nondeterministic" not actually random,
// so although we could just chop off the "front" of the // so although we could just chop off the "front" of the

View File

@ -37,6 +37,10 @@ func init() {
// `{http.auth.user.*}` placeholders may be set for any authentication // `{http.auth.user.*}` placeholders may be set for any authentication
// modules that provide user metadata. // modules that provide user metadata.
// //
// In case of an error, the placeholder `{http.auth.<provider>.error}`
// will be set to the error message returned by the authentication
// provider.
//
// Its API is still experimental and may be subject to change. // Its API is still experimental and may be subject to change.
type Authentication struct { type Authentication struct {
// A set of authentication providers. If none are specified, // A set of authentication providers. If none are specified,
@ -71,6 +75,7 @@ func (a *Authentication) Provision(ctx caddy.Context) error {
} }
func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
var user User var user User
var authed bool var authed bool
var err error var err error
@ -80,6 +85,9 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil { if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil {
c.Write(zap.String("provider", provName), zap.Error(err)) c.Write(zap.String("provider", provName), zap.Error(err))
} }
// Set the error from the authentication provider in a placeholder,
// so it can be used in the handle_errors directive.
repl.Set("http.auth."+provName+".error", err.Error())
continue continue
} }
if authed { if authed {
@ -90,7 +98,6 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated")) return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
} }
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
repl.Set("http.auth.user.id", user.ID) repl.Set("http.auth.user.id", user.ID)
for k, v := range user.Metadata { for k, v := range user.Metadata {
repl.Set("http.auth.user."+k, v) repl.Set("http.auth.user."+k, v)

View File

@ -26,7 +26,7 @@
<path d="M9 7l4 0"/> <path d="M9 7l4 0"/>
<path d="M9 11l4 0"/> <path d="M9 11l4 0"/>
</svg> </svg>
{{- else if .HasExt ".jpg" ".jpeg" ".png" ".gif" ".webp" ".tiff" ".bmp" ".heif" ".heic" ".svg"}} {{- else if .HasExt ".jpg" ".jpeg" ".png" ".gif" ".webp" ".tiff" ".bmp" ".heif" ".heic" ".svg" ".avif"}}
{{- if eq .Tpl.Layout "grid"}} {{- if eq .Tpl.Layout "grid"}}
<img loading="lazy" src="{{.Name | pathEscape}}"> <img loading="lazy" src="{{.Name | pathEscape}}">
{{- else}} {{- else}}
@ -802,7 +802,7 @@ footer {
<b>{{.NumFiles}}</b> file{{if ne 1 .NumFiles}}s{{end}} <b>{{.NumFiles}}</b> file{{if ne 1 .NumFiles}}s{{end}}
</span> </span>
<span class="meta-item"> <span class="meta-item">
<b>{{.HumanTotalFileSize}}</b> total <b>{{.HumanTotalFileSize}}</b> total
</span> </span>
{{- if ne 0 .Limit}} {{- if ne 0 .Limit}}
<span class="meta-item"> <span class="meta-item">
@ -828,6 +828,96 @@ footer {
</svg> </svg>
Grid Grid
</a> </a>
{{- if and (eq .Layout "grid") (eq .Sort "name") (ne .Order "asc")}}
<a href="?sort=name&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<text x="2" y="10" font-size="9" fill="currentColor">Z</text>
<text x="2" y="20" font-size="9" fill="currentColor">A</text>
<path d="M13 4v12"></path>
<path d="M12 16l1 2l1 -2"></path>
</svg>
</a>
{{- else if and (eq .Layout "grid") (eq .Sort "name") (ne .Order "desc")}}
<a href="?sort=name&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<text x="2" y="10" font-size="9" fill="currentColor">A</text>
<text x="2" y="20" font-size="9" fill="currentColor">Z</text>
<path d="M13 4v12"></path>
<path d="M12 16l1 2l1 -2"></path>
</svg>
</a>
{{- else if and (eq .Layout "grid")}}
<a href="?sort=name&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<text x="2" y="20" font-size="9" fill="currentColor">A</text>
<text x="2" y="10" font-size="9" fill="currentColor">Z</text>
<path d="M13 4v12"></path>
<path d="M12 16l1 2l1 -2"></path>
</svg>
</a>
{{- end}}
{{- if and (eq .Layout "grid") (eq .Sort "size") (ne .Order "asc")}}
<a href="?sort=size&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="4" width="4" height="3" rx="0.4" ry="0.4"></rect>
<rect x="2" y="10" width="8" height="3" rx="0.4" ry="0.4"></rect>
<rect x="2" y="16" width="12" height="3" rx="0.4" ry="0.4"></rect>
<path d="M18 4v12"></path>
<path d="M17 16l1 2l1 -2"></path>
</svg>
</a>
{{- else if and (eq .Layout "grid") (eq .Sort "size") (ne .Order "desc")}}
<a href="?sort=size&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="4" width="12" height="3" rx="0.4" ry="0.4"></rect>
<rect x="2" y="10" width="8" height="3" rx="0.4" ry="0.4"></rect>
<rect x="2" y="16" width="4" height="3" rx="0.4" ry="0.4"></rect>
<path d="M18 4v12"></path>
<path d="M17 16l1 2l1 -2"></path>
</svg>
</a>
{{- else if and (eq .Layout "grid")}}
<a href="?sort=size&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<rect x="2" y="4" width="4" height="3" rx="0.4" ry="0.4"></rect>
<rect x="2" y="10" width="8" height="3" rx="0.4" ry="0.4"></rect>
<rect x="2" y="16" width="12" height="3" rx="0.4" ry="0.4"></rect>
<path d="M18 4v12"></path>
<path d="M17 16l1 2l1 -2"></path>
</svg>
</a>
{{- end}}
{{- if and (eq .Layout "grid") (eq .Sort "time") (ne .Order "asc")}}
<a href="?sort=time&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<circle cx="9" cy="11" r="8"></circle>
<line x1="9" y1="12" x2="9" y2="7" stroke-linecap="round"></line>
<line x1="9" y1="12" x2="12" y2="12" stroke-linecap="round"></line>
<path d="M20 4v12"></path>
<path d="M19 16l1 2l1 -2"></path>
</svg>
</a>
{{- else if and (eq .Layout "grid") (eq .Sort "time") (ne .Order "desc")}}
<a href="?sort=time&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<circle cx="9" cy="11" r="8"></circle>
<line x1="9" y1="12" x2="9" y2="7" stroke-linecap="round"></line>
<line x1="9" y1="12" x2="12" y2="12" stroke-linecap="round"></line>
<path d="M20 4v12"></path>
<path d="M19 5l1 -2l1 2"></path>
</svg>
</a>
{{- else if and (eq .Layout "grid")}}
<a href="?sort=time&order=asc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}&layout=grid">
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-layout-grid" width="16" height="16" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
<circle cx="9" cy="11" r="8"></circle>
<line x1="9" y1="12" x2="9" y2="7" stroke-linecap="round"></line>
<line x1="9" y1="12" x2="12" y2="12" stroke-linecap="round"></line>
<path d="M20 4v12"></path>
<path d="M19 16l1 2l1 -2"></path>
</svg>
</a>
{{- end}}
</div> </div>
<div class='listing{{if eq .Layout "grid"}} grid{{end}}'> <div class='listing{{if eq .Layout "grid"}} grid{{end}}'>
{{- if eq .Layout "grid"}} {{- if eq .Layout "grid"}}
@ -868,7 +958,7 @@ footer {
</svg> </svg>
</a> </a>
{{- end}} {{- end}}
{{- if and (eq .Sort "name") (ne .Order "desc")}} {{- if and (eq .Sort "name") (ne .Order "desc")}}
<a href="?sort=name&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}"> <a href="?sort=name&order=desc{{if ne 0 .Limit}}&limit={{.Limit}}{{end}}{{if ne 0 .Offset}}&offset={{.Offset}}{{end}}">
Name Name

View File

@ -252,7 +252,7 @@ func celFileMatcherMacroExpander() parser.MacroExpander {
} }
for _, arg := range args { for _, arg := range args {
if !(isCELStringLiteral(arg) || isCELCaddyPlaceholderCall(arg)) { if !isCELStringLiteral(arg) && !isCELCaddyPlaceholderCall(arg) {
return nil, &common.Error{ return nil, &common.Error{
Location: eh.OffsetLocation(arg.ID()), Location: eh.OffsetLocation(arg.ID()),
Message: "matcher only supports repeated string literal arguments", Message: "matcher only supports repeated string literal arguments",
@ -274,7 +274,7 @@ func celFileMatcherMacroExpander() parser.MacroExpander {
func (m *MatchFile) Provision(ctx caddy.Context) error { func (m *MatchFile) Provision(ctx caddy.Context) error {
m.logger = ctx.Logger() m.logger = ctx.Logger()
m.fsmap = ctx.Filesystems() m.fsmap = ctx.FileSystems()
if m.Root == "" { if m.Root == "" {
m.Root = "{http.vars.root}" m.Root = "{http.vars.root}"
@ -616,15 +616,16 @@ func isCELTryFilesLiteral(e ast.Expr) bool {
return false return false
} }
mapKeyStr := mapKey.AsLiteral().ConvertToType(types.StringType).Value() mapKeyStr := mapKey.AsLiteral().ConvertToType(types.StringType).Value()
if mapKeyStr == "try_files" || mapKeyStr == "split_path" { switch mapKeyStr {
case "try_files", "split_path":
if !isCELStringListLiteral(mapVal) { if !isCELStringListLiteral(mapVal) {
return false return false
} }
} else if mapKeyStr == "try_policy" || mapKeyStr == "root" { case "try_policy", "root":
if !(isCELStringExpr(mapVal)) { if !(isCELStringExpr(mapVal)) {
return false return false
} }
} else { default:
return false return false
} }
} }

View File

@ -117,7 +117,7 @@ func TestFileMatcher(t *testing.T) {
}, },
} { } {
m := &MatchFile{ m := &MatchFile{
fsmap: &filesystems.FilesystemMap{}, fsmap: &filesystems.FileSystemMap{},
Root: "./testdata", Root: "./testdata",
TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/"}, TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/"},
} }
@ -229,7 +229,7 @@ func TestPHPFileMatcher(t *testing.T) {
}, },
} { } {
m := &MatchFile{ m := &MatchFile{
fsmap: &filesystems.FilesystemMap{}, fsmap: &filesystems.FileSystemMap{},
Root: "./testdata", Root: "./testdata",
TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/index.php"}, TryFiles: []string{"{http.request.uri.path}", "{http.request.uri.path}/index.php"},
SplitPath: []string{".php"}, SplitPath: []string{".php"},
@ -273,7 +273,7 @@ func TestPHPFileMatcher(t *testing.T) {
func TestFirstSplit(t *testing.T) { func TestFirstSplit(t *testing.T) {
m := MatchFile{ m := MatchFile{
SplitPath: []string{".php"}, SplitPath: []string{".php"},
fsmap: &filesystems.FilesystemMap{}, fsmap: &filesystems.FileSystemMap{},
} }
actual, remainder := m.firstSplit("index.PHP/somewhere") actual, remainder := m.firstSplit("index.PHP/somewhere")
expected := "index.PHP" expected := "index.PHP"

View File

@ -186,7 +186,7 @@ func (FileServer) CaddyModule() caddy.ModuleInfo {
func (fsrv *FileServer) Provision(ctx caddy.Context) error { func (fsrv *FileServer) Provision(ctx caddy.Context) error {
fsrv.logger = ctx.Logger() fsrv.logger = ctx.Logger()
fsrv.fsmap = ctx.Filesystems() fsrv.fsmap = ctx.FileSystems()
if fsrv.FileSystem == "" { if fsrv.FileSystem == "" {
fsrv.FileSystem = "{http.vars.fs}" fsrv.FileSystem = "{http.vars.fs}"
@ -300,8 +300,10 @@ func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
info, err := fs.Stat(fileSystem, filename) info, err := fs.Stat(fileSystem, filename)
if err != nil { if err != nil {
err = fsrv.mapDirOpenError(fileSystem, err, filename) err = fsrv.mapDirOpenError(fileSystem, err, filename)
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrInvalid) { if errors.Is(err, fs.ErrNotExist) {
return fsrv.notFound(w, r, next) return fsrv.notFound(w, r, next)
} else if errors.Is(err, fs.ErrInvalid) {
return caddyhttp.Error(http.StatusBadRequest, err)
} else if errors.Is(err, fs.ErrPermission) { } else if errors.Is(err, fs.ErrPermission) {
return caddyhttp.Error(http.StatusForbidden, err) return caddyhttp.Error(http.StatusForbidden, err)
} }
@ -611,6 +613,11 @@ func (fsrv *FileServer) mapDirOpenError(fileSystem fs.FS, originalErr error, nam
return originalErr return originalErr
} }
var pathErr *fs.PathError
if errors.As(originalErr, &pathErr) {
return fs.ErrInvalid
}
parts := strings.Split(name, separator) parts := strings.Split(name, separator)
for i := range parts { for i := range parts {
if parts[i] == "" { if parts[i] == "" {
@ -677,11 +684,11 @@ func fileHidden(filename string, hide []string) bool {
return true return true
} }
} }
} else if strings.HasPrefix(filename, h) { } else if after, ok := strings.CutPrefix(filename, h); ok {
// if there is a separator in h, and filename is exactly // if there is a separator in h, and filename is exactly
// prefixed with h, then we can do a prefix match so that // prefixed with h, then we can do a prefix match so that
// "/foo" matches "/foo/bar" but not "/foobar". // "/foo" matches "/foo/bar" but not "/foobar".
withoutPrefix := strings.TrimPrefix(filename, h) withoutPrefix := after
if strings.HasPrefix(withoutPrefix, separator) { if strings.HasPrefix(withoutPrefix, separator) {
return true return true
} }

View File

@ -118,6 +118,11 @@ func (irh interceptedResponseHandler) WriteHeader(statusCode int) {
irh.ResponseRecorder.WriteHeader(statusCode) irh.ResponseRecorder.WriteHeader(statusCode)
} }
// EXPERIMENTAL: Subject to change or removal.
func (irh interceptedResponseHandler) Unwrap() http.ResponseWriter {
return irh.ResponseRecorder
}
// EXPERIMENTAL: Subject to change or removal. // EXPERIMENTAL: Subject to change or removal.
func (ir Intercept) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { func (ir Intercept) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
buf := bufPool.Get().(*bytes.Buffer) buf := bufPool.Get().(*bytes.Buffer)

View File

@ -552,7 +552,6 @@ func (MatchPath) matchPatternWithEscapeSequence(escapedPath, matchPath string) b
if iPattern >= len(matchPath) || iPath >= len(escapedPath) { if iPattern >= len(matchPath) || iPath >= len(escapedPath) {
break break
} }
// get the next character from the request path // get the next character from the request path
pathCh := string(escapedPath[iPath]) pathCh := string(escapedPath[iPath])

View File

@ -9,8 +9,9 @@ import (
"sync" "sync"
"testing" "testing"
"github.com/caddyserver/caddy/v2"
"github.com/prometheus/client_golang/prometheus/testutil" "github.com/prometheus/client_golang/prometheus/testutil"
"github.com/caddyserver/caddy/v2"
) )
func TestServerNameFromContext(t *testing.T) { func TestServerNameFromContext(t *testing.T) {

View File

@ -363,13 +363,13 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
} }
} }
switch { switch key {
case key == "http.shutting_down": case "http.shutting_down":
server := req.Context().Value(ServerCtxKey).(*Server) server := req.Context().Value(ServerCtxKey).(*Server)
server.shutdownAtMu.RLock() server.shutdownAtMu.RLock()
defer server.shutdownAtMu.RUnlock() defer server.shutdownAtMu.RUnlock()
return !server.shutdownAt.IsZero(), true return !server.shutdownAt.IsZero(), true
case key == "http.time_until_shutdown": case "http.time_until_shutdown":
server := req.Context().Value(ServerCtxKey).(*Server) server := req.Context().Value(ServerCtxKey).(*Server)
server.shutdownAtMu.RLock() server.shutdownAtMu.RLock()
defer server.shutdownAtMu.RUnlock() defer server.shutdownAtMu.RUnlock()

Some files were not shown because too many files have changed in this diff Show More