From c0da7d487abcdcd9761220d75400f75584482b5f Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 21 Aug 2019 15:50:02 -0600 Subject: [PATCH] file_server: Automatically hide all involved Caddyfiles --- caddyconfig/httpcaddyfile/directives.go | 20 ++++++++++++++++++++ caddyconfig/httpcaddyfile/httptype.go | 1 + modules/caddyhttp/fileserver/caddyfile.go | 9 +++++++++ 3 files changed, 30 insertions(+) diff --git a/caddyconfig/httpcaddyfile/directives.go b/caddyconfig/httpcaddyfile/directives.go index 526ac87e..dad27bad 100644 --- a/caddyconfig/httpcaddyfile/directives.go +++ b/caddyconfig/httpcaddyfile/directives.go @@ -81,6 +81,26 @@ type Helper struct { *caddyfile.Dispenser warnings *[]caddyconfig.Warning matcherDefs map[string]map[string]json.RawMessage + parentBlock caddyfile.ServerBlock +} + +// Caddyfiles returns the list of config files from +// which tokens in the current server block were loaded. +func (h Helper) Caddyfiles() []string { + // first obtain set of names of files involved + // in this server block, without duplicates + files := make(map[string]struct{}) + for _, segment := range h.parentBlock.Segments { + for _, token := range segment { + files[token.File] = struct{}{} + } + } + // then convert the set into a slice + filesSlice := make([]string, 0, len(files)) + for file := range files { + filesSlice = append(filesSlice, file) + } + return filesSlice } // JSON converts val into JSON. Any errors are added to warnings. diff --git a/caddyconfig/httpcaddyfile/httptype.go b/caddyconfig/httpcaddyfile/httptype.go index e7e7c87c..00ce2cf2 100644 --- a/caddyconfig/httpcaddyfile/httptype.go +++ b/caddyconfig/httpcaddyfile/httptype.go @@ -95,6 +95,7 @@ func (st ServerType) Setup(originalServerBlocks []caddyfile.ServerBlock, Dispenser: caddyfile.NewDispenser(segment), warnings: &warnings, matcherDefs: matcherDefs, + parentBlock: sb.block, }) if err != nil { return nil, warnings, fmt.Errorf("parsing caddyfile tokens for '%s': %v", dir, err) diff --git a/modules/caddyhttp/fileserver/caddyfile.go b/modules/caddyhttp/fileserver/caddyfile.go index 6fa94e7b..902bd14c 100644 --- a/modules/caddyhttp/fileserver/caddyfile.go +++ b/modules/caddyhttp/fileserver/caddyfile.go @@ -76,6 +76,15 @@ func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) fsrv.Root = "{http.var.root}" } + // hide the Caddyfile (and any imported Caddyfiles) + if configFiles := h.Caddyfiles(); len(configFiles) > 0 { + for _, file := range configFiles { + if !fileHidden(file, fsrv.Hide) { + fsrv.Hide = append(fsrv.Hide, file) + } + } + } + return &fsrv, nil }