Skip to content

Commit b8e005d

Browse files
cisbiceanuCopilot
andauthored
[2.4.x] Backport mod_env SetEnvFromFile (#934)
[2.4.x] Backport mod_env SetEnvFromFile Backport trunk commit 837965f (r1938506). Include the stable-branch documentation, changelog, and test availability marker for 2.4.70. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> [2.4.x] Retarget SetEnvFromFile backport to 2.4.72 Apache 2.4.70 has already been released, and the 2.4.71-rc1 candidate does not contain SetEnvFromFile. Update the directive's documented availability and regression-test release threshold to the proposed 2.4.72 release. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> [2.4.x] Backport SetEnvFromFile read and quoting fixes Backport trunk commit 784e454 (#1004), addressing the review requests on #934. Reject non-EOF read failures with file and line diagnostics. Support SetEnv-style single- and double-quoted values, preserve quoted whitespace, and reject malformed quoting. Carry all accepted regression cases and XML guidance while retaining the 2.4.72 availability marker and stable-branch documentation formatting. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 864ea8d commit b8e005d

4 files changed

Lines changed: 349 additions & 4 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
*) mod_env: Add the SetEnvFromFile directive to set internal environment
2+
variables from a file of name=value lines, read at configuration time.
3+
[Cornel Isbiceanu <cisbiceanu adobe.com>]

‎docs/manual/mod/mod_env.xml‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,5 +118,89 @@ SSI pages</description>
118118
</usage>
119119
</directivesynopsis>
120120

121-
</modulesynopsis>
121+
<directivesynopsis>
122+
<name>SetEnvFromFile</name>
123+
<description>Sets environment variables from a file</description>
124+
<syntax>SetEnvFromFile <var>file-path</var></syntax>
125+
<contextlist><context>server config</context><context>virtual host</context>
126+
<context>directory</context></contextlist>
127+
<compatibility>Available in version 2.4.72 and later.</compatibility>
128+
129+
<usage>
130+
<p>Sets internal environment variables read from a file, which are then
131+
available to Apache HTTP Server modules, and passed on to CGI scripts and
132+
SSI pages. This is equivalent to a series of <directive
133+
module="mod_env">SetEnv</directive> directives, one per variable, but keeps
134+
the values in a separate file.</p>
135+
136+
<p>The <var>file-path</var> is either an absolute path or a path relative
137+
to the <directive module="core">ServerRoot</directive>. The file is read
138+
once when the configuration is parsed; changes to it take effect only after
139+
the server is restarted.</p>
140+
141+
<p>Each line of the file has the form <code>name=value</code>. Blank lines
142+
and lines beginning with <code>#</code> are ignored, and leading and
143+
trailing whitespace is stripped. If a line contains no <code>=</code>, the
144+
variable is set to an empty string. A line ending in a backslash
145+
(<code>\</code>) is continued on the following line, just as in the main
146+
configuration files.</p>
147+
148+
<p>A value beginning with a single or double quote (after any whitespace
149+
following <code>=</code>) is treated as quoted, as with
150+
<directive module="mod_env">SetEnv</directive>. The surrounding quotes
151+
are removed, and whitespace inside them is preserved. Whitespace before
152+
the opening quote or after the closing quote is ignored. Within a quoted
153+
value, a backslash escapes another backslash or the matching quote
154+
character; other backslashes are preserved. To include a literal quote,
155+
escape it inside a quoted value or use the other quote character to
156+
enclose the value. Unquoted values may contain spaces and are not
157+
unescaped. An unterminated quoted value or unexpected text after the
158+
closing quote causes a configuration error.</p>
159+
160+
<p>If the file cannot be read completely, including because a line
161+
(after joining continued lines) is too long, configuration parsing
162+
fails with an error identifying the file and line number.</p>
163+
164+
<example><title>Example using quoted values</title>
165+
<highlight language="config">
166+
SetEnvFromFile "conf/app.env"
167+
</highlight>
168+
</example>
169+
170+
<example><title>Example file (<code>conf/app.env</code>)</title>
171+
<highlight language="config">
172+
# Application settings
173+
APP_MODE=production
174+
SPECIAL_PATH=/foo/bin
175+
PADDED_VALUE=" value with surrounding spaces "
176+
EMPTY_VALUE=""
177+
LITERAL_QUOTE="'value"
178+
ESCAPED_QUOTE='\'value'
179+
</highlight>
180+
</example>
181+
182+
<note><p>As with <directive module="mod_env">SetEnv</directive>, the
183+
variables are set <em>after</em> most early request processing directives
184+
are run, such as access control and URI-to-filename mapping.</p>
185+
</note>
122186

187+
<note type="warning"><title>Security</title>
188+
<p>Unlike <directive module="mod_env">SetEnv</directive>, this directive
189+
reads the <em>contents</em> of a file into the internal environment, where
190+
they may be exposed through CGI, SSI, logging and other consumers. To
191+
prevent an untrusted author from disclosing the contents of any file
192+
readable by the server (for example configuration or credential files
193+
elsewhere on the host), <directive>SetEnvFromFile</directive> is
194+
<strong>not</strong> permitted in <code>.htaccess</code> files; it may only
195+
be used in the main server configuration.</p>
196+
</note>
197+
198+
</usage>
199+
200+
<seealso><a href="../env.html">Environment Variables</a></seealso>
201+
202+
<seealso><directive module="mod_env">SetEnv</directive></seealso>
203+
204+
</directivesynopsis>
205+
206+
</modulesynopsis>

‎modules/metadata/mod_env.c‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616

1717
#include "apr.h"
18+
#include "apr_lib.h"
1819
#include "apr_strings.h"
1920

2021
#if APR_HAVE_STDLIB_H
@@ -146,6 +147,95 @@ static const char *add_env_module_vars_unset(cmd_parms *cmd, void *sconf_,
146147
return NULL;
147148
}
148149

150+
static const char *add_env_module_vars_from_file(cmd_parms *cmd, void *sconf_,
151+
const char *arg)
152+
{
153+
env_dir_config_rec *sconf = sconf_;
154+
const char *fname;
155+
ap_configfile_t *file;
156+
apr_status_t rv;
157+
char line[MAX_STRING_LEN];
158+
159+
fname = ap_server_root_relative(cmd->temp_pool, arg);
160+
if (!fname) {
161+
return apr_pstrcat(cmd->pool, cmd->cmd->name,
162+
": Invalid file path ", arg, NULL);
163+
}
164+
165+
rv = ap_pcfg_openfile(&file, cmd->temp_pool, fname);
166+
if (rv != APR_SUCCESS) {
167+
return apr_psprintf(cmd->pool, "%s: Could not open file %s: %pm",
168+
cmd->cmd->name, fname, &rv);
169+
}
170+
171+
/* Each line is "name=value"; blank lines and '#' comments are ignored.
172+
* ap_cfg_getline() strips surrounding whitespace and handles line
173+
* continuations. Names are read at config time and stored in the same
174+
* table used by SetEnv, so they merge and reach r->subprocess_env the
175+
* same way.
176+
*/
177+
while ((rv = ap_cfg_getline(line, sizeof(line), file)) == APR_SUCCESS) {
178+
const char *rest = line;
179+
const char *name, *value, *quoted;
180+
181+
if (line[0] == '#' || line[0] == '\0') {
182+
continue;
183+
}
184+
185+
name = ap_getword(cmd->pool, &rest, '=');
186+
if (!name[0]) {
187+
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
188+
APLOGNO(10632) "%s: Skipping malformed line "
189+
"(no variable name) in %s", cmd->cmd->name, fname);
190+
continue;
191+
}
192+
193+
/* rest points just past the '='; no '=' means an empty value. */
194+
quoted = rest;
195+
while (apr_isspace(*quoted)) {
196+
++quoted;
197+
}
198+
if (*quoted == '"' || *quoted == '\'') {
199+
const char *end;
200+
201+
/* ap_getword_conf() does not report unterminated quotes. */
202+
for (end = quoted + 1; *end && *end != *quoted; ++end) {
203+
if (*end == '\\' && (end[1] == *quoted || end[1] == '\\')) {
204+
++end;
205+
}
206+
}
207+
if (!*end) {
208+
ap_cfg_closefile(file);
209+
return apr_psprintf(cmd->pool,
210+
"%s: Error reading %s at line %u: "
211+
"Unterminated quoted value",
212+
cmd->cmd->name, fname, file->line_number);
213+
}
214+
215+
value = ap_getword_conf(cmd->pool, &quoted);
216+
if (*quoted) {
217+
ap_cfg_closefile(file);
218+
return apr_psprintf(cmd->pool,
219+
"%s: Error reading %s at line %u: "
220+
"Unexpected text after quoted value",
221+
cmd->cmd->name, fname, file->line_number);
222+
}
223+
}
224+
else {
225+
value = apr_pstrdup(cmd->pool, rest);
226+
}
227+
apr_table_setn(sconf->vars, name, value);
228+
}
229+
230+
ap_cfg_closefile(file);
231+
232+
if (rv != APR_EOF) {
233+
return ap_pcfg_strerror(cmd->pool, file, rv);
234+
}
235+
236+
return NULL;
237+
}
238+
149239
static const command_rec env_module_cmds[] =
150240
{
151241
AP_INIT_ITERATE("PassEnv", add_env_module_vars_passed, NULL,
@@ -154,6 +244,9 @@ AP_INIT_TAKE12("SetEnv", add_env_module_vars_set, NULL,
154244
OR_FILEINFO, "an environment variable name and optional value to pass to CGI."),
155245
AP_INIT_ITERATE("UnsetEnv", add_env_module_vars_unset, NULL,
156246
OR_FILEINFO, "a list of variables to remove from the CGI environment."),
247+
AP_INIT_TAKE1("SetEnvFromFile", add_env_module_vars_from_file, NULL,
248+
RSRC_CONF | ACCESS_CONF,
249+
"the path to a file of name=value lines to pass to CGI."),
157250
{NULL},
158251
};
159252

‎test/modules/metadata/test_002_setenvfromfile.py‎

Lines changed: 168 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,18 @@
55
from pyhttpd.backport import skip_not_backported
66
from pyhttpd.conf import HttpdConf
77

8-
pytestmark = skip_not_backported("r1938506", "SetEnvFromFile")
8+
pytestmark = skip_not_backported("r1938506", "SetEnvFromFile",
9+
backported_in="2.4.72")
910

1011

11-
def _write_ssi_echo(path, names):
12+
def _write_ssi_echo(path, names, encoding="entity"):
1213
"""An SSI page echoing each variable as NAME=[value]. An unset
1314
variable echoes the default "(none)", so a set-but-empty variable
1415
("[]") is distinguishable from one that never made it into the table.
1516
"""
1617
with open(path, "w") as f:
1718
for name in names:
18-
f.write(f'{name}=[<!--#echo var="{name}" -->]\n')
19+
f.write(f'{name}=[<!--#echo encoding="{encoding}" var="{name}" -->]\n')
1920

2021

2122
class TestSetEnvFromFile:
@@ -204,3 +205,167 @@ def test_metadata_002_04_missing_file(self, env):
204205
good.add_vhost_test1()
205206
good.install()
206207
assert env.apache_restart() == 0
208+
209+
210+
class TestSetEnvFromFileConfig:
211+
212+
def check_config(self, env, contents):
213+
env_file = os.path.join(env.gen_dir, "setenv-read.env")
214+
with open(env_file, "w", newline="") as f:
215+
f.write(contents)
216+
217+
conf = HttpdConf(env, extras={
218+
'base': f'SetEnvFromFile "{env_file}"',
219+
})
220+
conf.add_vhost_test1()
221+
conf.install()
222+
return env.run([os.path.join(env.bin_dir, "httpd"),
223+
"-t", "-d", env.server_dir,
224+
"-f", os.path.join(env.server_dir, "conf", "httpd.conf")])
225+
226+
@pytest.mark.parametrize("line_length", [8191, 8192, 16384])
227+
@pytest.mark.parametrize("ending", ["\n", ""], ids=["newline", "eof"])
228+
def test_metadata_002_05_long_line(self, env, line_length, ending):
229+
line = "ENV_LONG=" + "x" * (line_length - len("ENV_LONG="))
230+
contents = "ENV_BEFORE=before\n" + line + ending
231+
if ending:
232+
contents += "ENV_AFTER=after\n"
233+
r = self.check_config(env, contents)
234+
assert r.exit_code != 0, "oversized line was accepted"
235+
assert "setenv-read.env at line 2: Line too long" in r.stderr
236+
237+
def test_metadata_002_06_long_continuation(self, env):
238+
r = self.check_config(
239+
env, "ENV_BEFORE=before\nENV_LONG=" + "x" * 4096
240+
+ "\\\n" + "y" * 4096 + "\nENV_AFTER=after\n")
241+
assert r.exit_code != 0, "oversized continued line was accepted"
242+
assert "setenv-read.env at line 3: Line too long" in r.stderr
243+
244+
# The 8192-byte buffer needs room for a newline and the terminating NUL.
245+
@pytest.mark.parametrize("contents", [
246+
pytest.param("", id="empty-file"),
247+
pytest.param("ENV_OK=present", id="no-final-newline"),
248+
pytest.param("ENV_OK=present\n", id="final-newline"),
249+
pytest.param("ENV_LONG=" + "x" * (8190 - len("ENV_LONG=")),
250+
id="max-line-no-newline"),
251+
pytest.param("ENV_LONG=" + "x" * (8190 - len("ENV_LONG=")) + "\n",
252+
id="max-line-with-newline"),
253+
pytest.param("ENV_LONG=" + "x" * 4096 + "\\\n"
254+
+ "y" * (8190 - len("ENV_LONG=") - 4096) + "\n",
255+
id="max-continued-line"),
256+
])
257+
def test_metadata_002_07_normal_eof(self, env, contents):
258+
r = self.check_config(env, contents)
259+
assert r.exit_code == 0, r.stderr
260+
261+
@pytest.mark.parametrize("value, message", [
262+
pytest.param('"unfinished', "Unterminated quoted value",
263+
id="unclosed-double"),
264+
pytest.param("'unfinished", "Unterminated quoted value",
265+
id="unclosed-single"),
266+
pytest.param('"', "Unterminated quoted value", id="double-quote-only"),
267+
pytest.param("'", "Unterminated quoted value", id="single-quote-only"),
268+
pytest.param(r'"escaped\"', "Unterminated quoted value",
269+
id="escaped-double-closer"),
270+
pytest.param(r"'escaped\'", "Unterminated quoted value",
271+
id="escaped-single-closer"),
272+
pytest.param('"closed"extra', "Unexpected text after quoted value",
273+
id="adjacent-text"),
274+
pytest.param("'closed' extra", "Unexpected text after quoted value",
275+
id="separate-text"),
276+
pytest.param('"" "extra"', "Unexpected text after quoted value",
277+
id="extra-quoted-token"),
278+
pytest.param(' \t"unfinished', "Unterminated quoted value",
279+
id="unclosed-after-whitespace"),
280+
])
281+
def test_metadata_002_11_malformed_quotes(self, env, value, message):
282+
r = self.check_config(
283+
env, f"ENV_BEFORE=before\nENV_BAD={value}\nENV_AFTER=after\n")
284+
assert r.exit_code != 0, "malformed quoted value was accepted"
285+
assert f"setenv-read.env at line 2: {message}" in r.stderr
286+
287+
288+
class TestSetEnvFromFileQuoted:
289+
290+
def check_value(self, env, file_value, expected):
291+
env_file = os.path.join(env.gen_dir, "setenv-quoted.env")
292+
with open(env_file, "w", newline="") as f:
293+
f.write(f"ENV_FILE={file_value}\nENV_AFTER=present\n")
294+
295+
doc_dir = os.path.join(env.server_dir, "htdocs", "test1")
296+
os.makedirs(doc_dir, exist_ok=True)
297+
_write_ssi_echo(os.path.join(doc_dir, "quoted.shtml"),
298+
["ENV_FILE", "ENV_DIRECT", "ENV_AFTER"], encoding="none")
299+
300+
direct_value = expected.replace("\\", "\\\\").replace('"', '\\"')
301+
conf = HttpdConf(env, extras={
302+
'base': f"""
303+
SetEnvFromFile "{env_file}"
304+
SetEnv ENV_DIRECT "{direct_value}"
305+
<Directory "{doc_dir}">
306+
Options +Includes
307+
AddType text/html .shtml
308+
AddOutputFilter INCLUDES .shtml
309+
</Directory>
310+
""",
311+
})
312+
conf.add_vhost_test1()
313+
conf.install()
314+
assert env.apache_restart() == 0
315+
316+
r = env.curl_get(env.mkurl("http", "test1", "/quoted.shtml"))
317+
assert r.response, "no response: server may have crashed"
318+
assert r.response["status"] == 200
319+
assert r.response["body"].decode("utf-8").splitlines() == [
320+
f"ENV_FILE=[{expected}]",
321+
f"ENV_DIRECT=[{expected}]",
322+
"ENV_AFTER=[present]",
323+
]
324+
325+
@pytest.mark.parametrize("quote", ['"', "'"], ids=["double", "single"])
326+
@pytest.mark.parametrize("expected", [
327+
pytest.param("hello", id="plain"),
328+
pytest.param("hello ", id="trailing-space"),
329+
pytest.param(" hello", id="leading-space"),
330+
pytest.param(" hello ", id="surrounding-spaces"),
331+
pytest.param("", id="empty"),
332+
pytest.param(" \t ", id="whitespace-only"),
333+
pytest.param("hello world", id="embedded-space"),
334+
pytest.param('say "hello" and \'bye\'', id="quote-escaping"),
335+
pytest.param('"unfinished', id="literal-double-quote-prefix"),
336+
pytest.param("'unfinished", id="literal-single-quote-prefix"),
337+
pytest.param('"hello"', id="literal-double-quotes"),
338+
pytest.param("'hello'", id="literal-single-quotes"),
339+
pytest.param(r"C:\app\file", id="backslash-escaping"),
340+
pytest.param("C:\\app\\", id="trailing-backslash"),
341+
pytest.param(r"\n\t", id="literal-escapes"),
342+
pytest.param("key=value # literal", id="equals-and-hash"),
343+
])
344+
def test_metadata_002_08_quoted(self, env, quote, expected):
345+
value = expected.replace("\\", "\\\\").replace(quote, "\\" + quote)
346+
self.check_value(env, quote + value + quote, expected)
347+
348+
@pytest.mark.parametrize("quote", ['"', "'"], ids=["double", "single"])
349+
def test_metadata_002_09_quoted_whitespace(self, env, quote):
350+
self.check_value(env, f" \t{quote} hello {quote} \t", " hello ")
351+
352+
@pytest.mark.parametrize("quote", ['"', "'"], ids=["double", "single"])
353+
def test_metadata_002_10_quoted_continuation(self, env, quote):
354+
self.check_value(env, f"{quote}first \\\nsecond {quote}", "first second ")
355+
356+
@pytest.mark.parametrize("file_value, expected", [
357+
pytest.param("hello world", "hello world", id="embedded-space"),
358+
pytest.param(" hello world ", " hello world", id="whitespace"),
359+
pytest.param(r"C:\app\file", r"C:\app\file", id="literal-backslashes"),
360+
pytest.param(r"a\\b", r"a\\b", id="doubled-backslash"),
361+
pytest.param('hello "world"', 'hello "world"', id="embedded-quotes"),
362+
pytest.param("", "", id="empty"),
363+
pytest.param(" ", "", id="whitespace-only"),
364+
])
365+
def test_metadata_002_12_unquoted(self, env, file_value, expected):
366+
self.check_value(env, file_value, expected)
367+
368+
@pytest.mark.parametrize("quote", ['"', "'"], ids=["double", "single"])
369+
def test_metadata_002_13_literal_escapes(self, env, quote):
370+
value = r"C:\app\n\t"
371+
self.check_value(env, quote + value + quote, value)

0 commit comments

Comments
 (0)