From 946b3cca8ff85baa2380a909810e9c0208e981b4 Mon Sep 17 00:00:00 2001
From: Hafiar <289389248+0xABCD01@users.noreply.github.com>
Date: Tue, 3 Nov 2026 11:34:34 +0000
Subject: [PATCH 1/2] mod_authn_socache: Keep cache entries separate for each
AuthName, authn provider and server port:
* modules/aaa/mod_authn_socache.c (construct_key): Take the provider
name. Add it, the AuthName for Basic auth, and for the "directory"
and "server" contexts the port configured for the server, to the
key.
(ap_authn_cache_store): Pass the provider name.
(check_password, get_realm_hash): Try the key for each provider
cached for.
* docs/manual/mod/mod_authn_socache.xml: Update AuthnCacheContext to
match.
* test/modules/aaa/test_016_authn_socache.py
(_SocacheBase.url, _SocacheBase.basic): Take a port.
(TestAuthnSocache._class_scope): Add locations and a second server
for the tests below.
(TestAuthnSocache.test_authn_socache_175_files_authname,
TestAuthnSocache.test_authn_socache_176_second_provider,
TestAuthnSocache.test_authn_socache_177_host_port,
TestAuthnSocache.test_authn_socache_178_server_port): New tests.
* changes-entries/authn_socache_key.txt: New file.
Submitted by: Hafiar <289389248+0xABCD01 users.noreply.github.com>
Reviewed by: jorton (committed with changes)
Github: closes #930
Co-Authored-By: Claude Fable 5.2
---
changes-entries/authn_socache_key.txt | 3 +
docs/manual/mod/mod_authn_socache.xml | 48 +++++++---
modules/aaa/mod_authn_socache.c | 102 ++++++++++++++++-----
test/modules/aaa/test_016_authn_socache.py | 81 +++++++++++++++-
4 files changed, 194 insertions(+), 40 deletions(-)
create mode 100644 changes-entries/authn_socache_key.txt
diff --git a/changes-entries/authn_socache_key.txt b/changes-entries/authn_socache_key.txt
new file mode 100644
index 00000000000..7be3f9462d8
--- /dev/null
+++ b/changes-entries/authn_socache_key.txt
@@ -0,0 +1,3 @@
+ *) mod_authn_socache: Keep cached credentials separate for each
+ AuthName and authn provider, and for each server port unless
+ AuthnCacheContext names a custom context. [Hafiar]
diff --git a/docs/manual/mod/mod_authn_socache.xml b/docs/manual/mod/mod_authn_socache.xml
index d00779b9c5d..a1c50ee6737 100644
--- a/docs/manual/mod/mod_authn_socache.xml
+++ b/docs/manual/mod/mod_authn_socache.xml
@@ -232,20 +232,44 @@ AuthnCacheProvideFor dbd myprovider
directory
- This directive specifies a string to be used along with the supplied
- username (and realm in the case of Digest Authentication) in constructing
- a cache key. This serves to disambiguate identical usernames serving
- different authentication areas on the server.
+ This directive specifies a string to be used along with the name of
+ the provider that produced the entry, the supplied username, and the
+ realm (for Basic Authentication, the protection space named by
+ AuthName) in
+ constructing a cache key. This serves to disambiguate identical
+ usernames serving different authentication areas on the server.
Two special values for this are directory, which uses
- the directory context of the request as a string, and server
- which uses the virtual host name.
- The default is directory, which is also the most
- conservative setting. This is likely to be less than optimal, as it
- (for example) causes $app-base, $app-base/images,
- $app-base/scripts and $app-base/media each to
- have its own separate cache key. A better policy is to name the
+ the server (hostname and port) and the directory of the request URI,
+ and server, which uses the virtual host name and port.
+ The default is directory. The default separates
+ backend provider results only where the directory-like URL path, the
+ provider, or the AuthName differs. A configuration
+ that varies the credential source within a single directory and a
+ single AuthName — for
+ example Files
+ sections with different AuthUserFile settings — must give
+ each source its own AuthName or its own custom
+ AuthnCacheContext; otherwise the sources share
+ cache entries, and a password valid for one source is accepted for
+ the others.
+ The directory context causes $app-base,
+ $app-base/images, $app-base/scripts and
+ $app-base/media each to have its own separate cache
+ entries. Where a whole directory tree is a single authentication
+ area backed by one credential source, name the
AuthnCacheContext for the password
- provider: for example a htpasswd file or database table.
+ provider instead: for example a htpasswd file or database
+ table, and use that one context for the whole area.
+ A shared custom context is only safe where every request in its
+ scope is checked against the same credential source. If different
+ credential sources are used within the scope of one custom context
+ (different password files, database tables, or queries for
+ different resources), entries are shared between them, and a
+ password valid for one source will be accepted for the others.
+ Give each distinct credential source its own context.
Contexts can be shared across different areas of a server, where
credentials are shared. However, this has potential to become a vector
for cross-site or cross-application security breaches, so this directive
diff --git a/modules/aaa/mod_authn_socache.c b/modules/aaa/mod_authn_socache.c
index 53eb3b9af77..e0a3d87e55f 100644
--- a/modules/aaa/mod_authn_socache.c
+++ b/modules/aaa/mod_authn_socache.c
@@ -267,28 +267,61 @@ static const command_rec authn_cache_cmds[] =
};
static const char *construct_key(request_rec *r, const char *context,
- const char *user, const char *realm)
+ const char *provider, const char *user,
+ const char *realm)
{
- const char *slash = ap_strrchr_c(r->uri, '/');
/* handle "special" context values */
- if (!strcmp(context, directory) && slash) {
- char *new_context;
- new_context = apr_palloc(r->pool, slash - r->uri +
- strlen(r->server->server_hostname) + 1);
- strcpy(new_context, r->server->server_hostname);
- strncat(new_context, r->uri, slash - r->uri);
- context = new_context;
+ if (!strcmp(context, directory)) {
+ const char *slash = ap_strrchr_c(r->uri, '/');
+ /* The port is that configured for the server, not
+ * ap_get_server_port(), which the client can choose in the
+ * Host header.
+ *
+ * The directory context identifies an entry by the server and
+ * the directory of the request URI. Within one directory,
+ * entries are separated by the provider and realm mixed into
+ * the key below; a configuration that varies the credential
+ * source within a single directory and realm (for example
+ * sections with different AuthUserFile settings) must
+ * use distinct AuthName values or a custom AuthnCacheContext
+ * to keep the sources apart, as the documentation states.
+ */
+ if (slash) {
+ context = apr_psprintf(r->pool, "%s:%u%.*s",
+ r->server->server_hostname,
+ (unsigned)r->server->port,
+ (int)(slash - r->uri), r->uri);
+ }
+ else {
+ context = apr_psprintf(r->pool, "%s:%u%s",
+ r->server->server_hostname,
+ (unsigned)r->server->port, r->uri);
+ }
}
else if (!strcmp(context, "server")) {
- context = r->server->server_hostname;
+ context = apr_psprintf(r->pool, "%s:%u",
+ r->server->server_hostname,
+ (unsigned)r->server->port);
}
/* any other context value is literal */
- if (realm == NULL) { /* basic auth */
- return apr_pstrcat(r->pool, context, ":", user, NULL);
+ if (realm == NULL) {
+ /* Basic auth: the protection space (AuthName) is the realm. */
+ realm = ap_auth_name(r);
+ }
+
+ /* The key is bound to the provider that produced the entry, so a
+ * hash stored by one credential source is never validated against
+ * a request for another, and to the realm, so entries are not
+ * shared between protection spaces.
+ */
+ if (realm == NULL) {
+ return apr_pstrcat(r->pool, context, ":", provider, ":", user,
+ NULL);
}
- else { /* digest auth */
- return apr_pstrcat(r->pool, context, ":", user, ":", realm, NULL);
+ else {
+ return apr_pstrcat(r->pool, context, ":", provider, ":", user,
+ ":", realm, NULL);
}
}
@@ -327,7 +360,7 @@ static void ap_authn_cache_store(request_rec *r, const char *module,
/* We have the mutex, so go ahead */
/* first build our key and determine expiry time */
- key = construct_key(r, dcfg->context, user, realm);
+ key = construct_key(r, dcfg->context, module, user, realm);
expiry = apr_time_now() + dcfg->timeout;
/* store it */
@@ -371,14 +404,27 @@ static authn_status check_password(request_rec *r, const char *user,
authn_cache_dircfg *dcfg;
unsigned char val[MAX_VAL_LEN];
unsigned int vallen = MAX_VAL_LEN - 1;
+ int i;
dcfg = ap_get_module_config(r->per_dir_config, &authn_socache_module);
if (!configured || !dcfg->providers) {
return AUTH_USER_NOT_FOUND;
}
- key = construct_key(r, dcfg->context, user, NULL);
- rv = socache_provider->retrieve(socache_instance, r->server,
- (unsigned char*)key, strlen(key),
- val, &vallen, r->pool);
+ /* Entries are stored under the key of the provider that produced
+ * them; try each provider this configuration caches for.
+ */
+ rv = APR_NOTFOUND;
+ for (i = 0; i < dcfg->providers->nelts; i++) {
+ const char *provider = APR_ARRAY_IDX(dcfg->providers, i,
+ const char *);
+ vallen = MAX_VAL_LEN - 1;
+ key = construct_key(r, dcfg->context, provider, user, NULL);
+ rv = socache_provider->retrieve(socache_instance, r->server,
+ (unsigned char*)key, strlen(key),
+ val, &vallen, r->pool);
+ if (rv == APR_SUCCESS || !APR_STATUS_IS_NOTFOUND(rv)) {
+ break;
+ }
+ }
if (APR_STATUS_IS_NOTFOUND(rv)) {
/* not found - just return */
@@ -416,14 +462,24 @@ static authn_status get_realm_hash(request_rec *r, const char *user,
authn_cache_dircfg *dcfg;
unsigned char val[MAX_VAL_LEN];
unsigned int vallen = MAX_VAL_LEN - 1;
+ int i;
dcfg = ap_get_module_config(r->per_dir_config, &authn_socache_module);
if (!configured || !dcfg->providers) {
return AUTH_USER_NOT_FOUND;
}
- key = construct_key(r, dcfg->context, user, realm);
- rv = socache_provider->retrieve(socache_instance, r->server,
- (unsigned char*)key, strlen(key),
- val, &vallen, r->pool);
+ rv = APR_NOTFOUND;
+ for (i = 0; i < dcfg->providers->nelts; i++) {
+ const char *provider = APR_ARRAY_IDX(dcfg->providers, i,
+ const char *);
+ vallen = MAX_VAL_LEN - 1;
+ key = construct_key(r, dcfg->context, provider, user, realm);
+ rv = socache_provider->retrieve(socache_instance, r->server,
+ (unsigned char*)key, strlen(key),
+ val, &vallen, r->pool);
+ if (rv == APR_SUCCESS || !APR_STATUS_IS_NOTFOUND(rv)) {
+ break;
+ }
+ }
if (APR_STATUS_IS_NOTFOUND(rv)) {
/* not found - just return */
diff --git a/test/modules/aaa/test_016_authn_socache.py b/test/modules/aaa/test_016_authn_socache.py
index 3f093c1c8ce..9bd85247b93 100644
--- a/test/modules/aaa/test_016_authn_socache.py
+++ b/test/modules/aaa/test_016_authn_socache.py
@@ -109,12 +109,16 @@ def basic_pwfile2(cls, env):
def digest_pwfile(cls, env):
return os.path.join(env.server_dir, "socache-digest.passwd")
- def url(self, env, name, fname="secret.txt"):
- return env.mkurl("http", "aaa", f"/socache/{name}/{fname}")
-
- def basic(self, env, name, user, password, fname="secret.txt"):
+ def url(self, env, name, fname="secret.txt", port=None):
+ url = env.mkurl("http", "aaa", f"/socache/{name}/{fname}")
+ if port:
+ url = url.replace(f":{env.http_port}/", f":{port}/")
+ return url
+
+ def basic(self, env, name, user, password, fname="secret.txt",
+ port=None):
"""The status of a Basic authenticated request."""
- r = env.curl_get(self.url(env, name, fname),
+ r = env.curl_get(self.url(env, name, fname, port),
options=["-u", f"{user}:{password}"])
assert r.exit_code == 0, r.stderr
if r.response["status"] == 200:
@@ -160,6 +164,8 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
# Caches for a provider which is not the one in use.
("other", ['AuthnCacheProvideFor dbm']),
("none", []),
+ # The provider in use is not the first one cached for.
+ ("second", ['AuthnCacheProvideFor dbm file']),
("dir1", cached),
("dir2", cached),
("literal1", cached + ['AuthnCacheContext shared']),
@@ -175,6 +181,7 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
for name, other_lines in [
("files", []),
("files-context", ['AuthnCacheContext other-file']),
+ ("files-authname", ['AuthName "AAA Other Realm"']),
]:
conf.add(_directory(env, name, [
*_basic_lines(basic_pwfile, cached),
@@ -189,6 +196,12 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
]:
conf.add(_directory(env, name,
_digest_lines(digest_pwfile, cache_lines)))
+ # A second server of the same name on another port, to which the
+ # sections above apply as well.
+ conf.add(f'Listen {env.http_port2}')
+ conf.start_vhost(domains=[f"aaa.{env.http_tld}"],
+ port=env.http_port2, doc_root=env.server_docs_dir)
+ conf.end_vhost()
with env.preserved_test_conf():
conf.install()
assert env.apache_restart() == 0
@@ -376,6 +389,64 @@ def test_authn_socache_174_files_context(
assert self.basic(env, "files-context", user, P1) == 200
assert self.basic(env, "files-context", user, P2, OTHER) == 200
+ def test_authn_socache_175_files_authname(
+ self, env, basic_pwfile, basic_pwfile2):
+ """An AuthName of its own keeps the entries for a document with
+ a different password file apart from those of the rest of the
+ directory."""
+ user = "user175"
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
+ AAATestEnv.write_basic_pwfile(basic_pwfile2, {user: P2})
+ for _ in range(2):
+ # first from the password files, then from the cache
+ assert self.basic(env, "files-authname", user, P1) == 200
+ assert self.basic(env, "files-authname", user, P1, OTHER) == 401
+ assert self.basic(env, "files-authname", user, P2, OTHER) == 200
+ assert self.basic(env, "files-authname", user, P2) == 401
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {})
+ AAATestEnv.write_basic_pwfile(basic_pwfile2, {})
+ assert self.basic(env, "files-authname", user, P1) == 200
+ assert self.basic(env, "files-authname", user, P2, OTHER) == 200
+
+ def test_authn_socache_176_second_provider(self, env, basic_pwfile):
+ """An entry is found whichever of the providers named by
+ AuthnCacheProvideFor stored it."""
+ user = "user176"
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
+ assert self.basic(env, "second", user, P1) == 200
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P2})
+ assert self.basic(env, "second", user, P1) == 200
+ assert self.basic(env, "second", user, P2) == 401
+
+ def test_authn_socache_177_host_port(self, env, basic_pwfile):
+ """The port a client puts in the Host header has no part in
+ finding an entry, so cannot be used to avoid or fill the
+ cache."""
+ user = "user177"
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
+ assert self.basic(env, "basic", user, P1) == 200
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P2})
+ for port in 1, 65535:
+ r = env.curl_get(self.url(env, "basic"), options=[
+ "-u", f"{user}:{P1}",
+ "-H", f"Host: aaa.{env.http_tld}:{port}"])
+ assert r.response["status"] == 200
+
+ @pytest.mark.parametrize("name", ["basic", "server1"])
+ def test_authn_socache_178_server_port(self, env, basic_pwfile, name):
+ """Servers of the same name on different ports do not share
+ entries, with the "directory" or the "server" AuthnCacheContext."""
+ user = f"user178{name}"
+ port2 = env.http_port2
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
+ assert self.basic(env, name, user, P1) == 200
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P2})
+ assert self.basic(env, name, user, P1, port=port2) == 401
+ assert self.basic(env, name, user, P2, port=port2) == 200
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {})
+ assert self.basic(env, name, user, P1) == 200
+ assert self.basic(env, name, user, P2, port=port2) == 200
+
class TestAuthnSocacheHtaccess(_SocacheBase):
"""AuthnCacheProvideFor given only in .htaccess files."""
From 9ed68fe9bb84e8877fa4fa962323ad769f360893 Mon Sep 17 00:00:00 2001
From: Joe Orton
Date: Mon, 16 Nov 2026 19:51:15 +0000
Subject: [PATCH 2/2] mod_authn_socache: Add the auth type to the cache key:
* modules/aaa/mod_authn_socache.c (construct_key): Add the lower-cased
AuthType to the key.
* docs/manual/mod/mod_authn_socache.xml: Document it.
* test/modules/aaa/test_016_authn_socache.py
(TestAuthnSocache._class_scope): Add Basic and Digest locations
sharing a context and AuthName.
(TestAuthnSocache.test_authn_socache_179_auth_type): New test.
* changes-entries/authn_socache_key.txt: Update.
Co-Authored-By: Claude Fable 5.2
---
changes-entries/authn_socache_key.txt | 4 ++--
docs/manual/mod/mod_authn_socache.xml | 5 ++--
modules/aaa/mod_authn_socache.c | 18 ++++++++++----
test/modules/aaa/test_016_authn_socache.py | 28 ++++++++++++++++++++++
4 files changed, 46 insertions(+), 9 deletions(-)
diff --git a/changes-entries/authn_socache_key.txt b/changes-entries/authn_socache_key.txt
index 7be3f9462d8..1b0891ac5e4 100644
--- a/changes-entries/authn_socache_key.txt
+++ b/changes-entries/authn_socache_key.txt
@@ -1,3 +1,3 @@
*) mod_authn_socache: Keep cached credentials separate for each
- AuthName and authn provider, and for each server port unless
- AuthnCacheContext names a custom context. [Hafiar]
+ AuthType, AuthName and authn provider, and for each server port
+ unless AuthnCacheContext names a custom context. [Hafiar]
diff --git a/docs/manual/mod/mod_authn_socache.xml b/docs/manual/mod/mod_authn_socache.xml
index a1c50ee6737..26d639ee1ce 100644
--- a/docs/manual/mod/mod_authn_socache.xml
+++ b/docs/manual/mod/mod_authn_socache.xml
@@ -233,8 +233,9 @@ AuthnCacheProvideFor dbd myprovider
This directive specifies a string to be used along with the name of
- the provider that produced the entry, the supplied username, and the
- realm (for Basic Authentication, the protection space named by
+ the provider that produced the entry, the AuthType, the supplied username,
+ and the realm (for Basic Authentication, the protection space named by
AuthName) in
constructing a cache key. This serves to disambiguate identical
usernames serving different authentication areas on the server.
diff --git a/modules/aaa/mod_authn_socache.c b/modules/aaa/mod_authn_socache.c
index e0a3d87e55f..9b183041db1 100644
--- a/modules/aaa/mod_authn_socache.c
+++ b/modules/aaa/mod_authn_socache.c
@@ -270,6 +270,12 @@ static const char *construct_key(request_rec *r, const char *context,
const char *provider, const char *user,
const char *realm)
{
+ const char *type = ap_auth_type(r);
+ char *ltype = apr_pstrdup(r->pool, type ? type : "");
+
+ /* AuthType is not case-sensitive. */
+ ap_str_tolower(ltype);
+
/* handle "special" context values */
if (!strcmp(context, directory)) {
const char *slash = ap_strrchr_c(r->uri, '/');
@@ -313,15 +319,17 @@ static const char *construct_key(request_rec *r, const char *context,
/* The key is bound to the provider that produced the entry, so a
* hash stored by one credential source is never validated against
* a request for another, and to the realm, so entries are not
- * shared between protection spaces.
+ * shared between protection spaces. It is bound to the auth type
+ * since what is cached differs between them: a password hash for
+ * Basic, the hash of user, realm and password for Digest.
*/
if (realm == NULL) {
- return apr_pstrcat(r->pool, context, ":", provider, ":", user,
- NULL);
+ return apr_pstrcat(r->pool, context, ":", provider, ":", ltype,
+ ":", user, NULL);
}
else {
- return apr_pstrcat(r->pool, context, ":", provider, ":", user,
- ":", realm, NULL);
+ return apr_pstrcat(r->pool, context, ":", provider, ":", ltype,
+ ":", user, ":", realm, NULL);
}
}
diff --git a/test/modules/aaa/test_016_authn_socache.py b/test/modules/aaa/test_016_authn_socache.py
index 9bd85247b93..5c441fca2a0 100644
--- a/test/modules/aaa/test_016_authn_socache.py
+++ b/test/modules/aaa/test_016_authn_socache.py
@@ -193,9 +193,16 @@ def _class_scope(cls, env, request, basic_pwfile, basic_pwfile2,
for name, cache_lines in [
("digest", cached),
("digest-none", []),
+ ("mixed-digest", cached + ['AuthnCacheContext mixed']),
]:
conf.add(_directory(env, name,
_digest_lines(digest_pwfile, cache_lines)))
+ # Basic, with the context and AuthName of "mixed-digest".
+ conf.add(_directory(env, "mixed-basic", [
+ *_basic_lines(basic_pwfile,
+ cached + ['AuthnCacheContext mixed']),
+ f'AuthName "{AAATestEnv.REALM}"',
+ ]))
# A second server of the same name on another port, to which the
# sections above apply as well.
conf.add(f'Listen {env.http_port2}')
@@ -447,6 +454,27 @@ def test_authn_socache_178_server_port(self, env, basic_pwfile, name):
assert self.basic(env, name, user, P1) == 200
assert self.basic(env, name, user, P2, port=port2) == 200
+ @pytest.mark.parametrize("first", ["basic", "digest"])
+ def test_authn_socache_179_auth_type(
+ self, env, basic_pwfile, digest_pwfile, first):
+ """Basic and Digest locations with the same AuthnCacheContext
+ and AuthName do not share entries, which are of no use to each
+ other."""
+ user = f"user179{first}"
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {user: P1})
+ env.write_digest_pwfile(digest_pwfile, {user: P1})
+ if first == "basic":
+ assert self.basic(env, "mixed-basic", user, P1) == 200
+ assert self.digest(env, "mixed-digest", user, P1) == 200
+ else:
+ assert self.digest(env, "mixed-digest", user, P1) == 200
+ assert self.basic(env, "mixed-basic", user, P1) == 200
+ # and both are now cached
+ AAATestEnv.write_basic_pwfile(basic_pwfile, {})
+ env.write_digest_pwfile(digest_pwfile, {})
+ assert self.basic(env, "mixed-basic", user, P1) == 200
+ assert self.digest(env, "mixed-digest", user, P1) == 200
+
class TestAuthnSocacheHtaccess(_SocacheBase):
"""AuthnCacheProvideFor given only in .htaccess files."""