Skip to content

Commit 89d65c2

Browse files
authored
[#37482] YSQL: Use the role's own yb_password_validity when another role sets its password (#37786)
## Summary ### Problem When CREATE ROLE or ALTER ROLE stores a password without `VALID UNTIL`, it sets `rolvaliduntil` to now() plus the `yb_password_validity` value, and each role can have its own value. Say role app_user has its own 30d (`ALTER ROLE app_user SET yb_password_validity = '30d'`) and role admin resets app_user's password: app_user should get now() + 30 days, but the value comes from admin instead: | admin's own value | app_user's expiry after admin's reset (before the fix) | After the fix | | --- | --- | --- | | 0 (default) | unchanged: app_user's old `rolvaliduntil` is written back | now() + 30 days | | 20d | now() + 20 days | now() + 30 days | With admin at 0, an expired app_user stays locked out after the reset, and if admin is a password vault that rotates app_user's password, the rotations never push app_user's expiry out. `CREATE ROLE ... PASSWORD` has the same problem: a role that admin creates gets admin's value. ```sql -- as admin, a superuser whose value is 0 CREATE ROLE app_user LOGIN PASSWORD 'p1' VALID UNTIL '2020-01-01'; ALTER ROLE app_user SET yb_password_validity = '30d'; ALTER ROLE app_user PASSWORD 'p2'; SELECT rolvaliduntil FROM pg_authid WHERE rolname = 'app_user'; -- without the fix: 2020-01-01 00:00:00 (app_user still cannot log in) -- with the fix: now() + 30 days ``` ### RCA `YbComputePasswordValidUntil()` uses the session's `yb_password_validity`, which a login loads for the role that logs in, so in the example admin's value is used for app_user. 482a44e ([#33480]) added the setting. 2026.2, 2026.1 and 2025.2 have the same code. PostgreSQL is not affected: it has no duration-based expiry. ### Fix When the statement gives `VALID UNTIL`, that date is used. Otherwise use the target role's own value: check these in order and use the first one that is set: 1. the role's own value (`ALTER ROLE <role> SET`) - A role being created (CREATE ROLE) has no value of its own yet, so this step is skipped. 2. the value for all roles (`ALTER ROLE ALL SET`) 3. the value in ysql_pg.conf (ysql_pg_conf_csv) 4. the default value This is the same order the role's own login applies them in ([`process_settings()`](https://github.com/yugabyte/yugabyte-db/blob/53ca95749813802e0ff54df29a7444300f9fd0f1/src/postgres/src/backend/utils/init/postinit.c#L2076-L2080)). When app_user changes its own password, the value its login loaded is used, as with any `ALTER ROLE ... SET`: a change to app_user's setting made after app_user logged in applies from its next login. For step 3, each process saves the password settings from ysql_pg.conf whenever it loads the file (at startup and on each reload), because a session whose login role has its own value keeps no copy of the file's value. ## Test plan | Case | Without the fix | With the fix | Test | | --- | --- | --- | --- | | admin (no value) resets app_user (own 30d, expired in 2020), the issue's repro | Still expired | 30 days | yb.orig.password_valid_until | | admin (own 20d) resets app_user (own 30d) | 20 days | 30 days | yb.orig.password_valid_until | | admin (own 20d) changes app_user's (own 30d) password after `SET SESSION AUTHORIZATION app_user`, and from a `SECURITY DEFINER` function owned by app_user | 20 days | 30 days | yb.orig.password_valid_until | | admin (own 20d) resets app_user (own 0) | 20 days | No expiry | yb.orig.password_valid_until | | admin (own 20d) resets app_user (no value) and creates a role, with `ALTER ROLE ALL SET` 40d | 20 days | 40 days | yb.orig.password_valid_until | | The same, with no `ALTER ROLE ALL SET` | 20 days | No expiry (the default, 0) | yb.orig.password_valid_until | | 50d in ysql_pg_conf_csv: a superuser (no value) resets app_user (no value) | 50 days | 50 days | TestPgPasswordValidity | | 50d in ysql_pg_conf_csv and `ALTER ROLE ALL SET` 30d: a superuser (no value) resets app_user (no value) | 50 days | 30 days | TestPgPasswordValidity | | 50d in ysql_pg_conf_csv: the superuser resets a role with its own 0 | 50 days | No expiry | TestPgPasswordValidity | | 50d in ysql_pg_conf_csv: admin (own 0) resets app_user (no value) and creates new_user | app_user unchanged, new_user no expiry | 50 days for both | TestPgPasswordValidity | | ysql_pg.conf changed to 20d, then to an invalid value, then with no line, each followed by a reload: admin (own 0, one session throughout) resets app_user (no value) after each | Expiry unchanged each time | 20 days; 20 days (the invalid value is ignored); no expiry (the default) | TestPgPasswordValidity | | A superuser logs in with its own 10d, sets its own value to 25d, then changes its own password in that session | 10 days | 10 days, the value its login loaded | yb.orig.password_valid_until | | A superuser (own reuse limit 0) resets the password of a role with no limit of its own; the limit in ysql_pg_conf_csv is 3 | Keeps all 4 passwords | Keeps the 3 newest | yb.orig.password_history | With the fix, the four tests below pass on a fastdebug build (clang21), directly and through YSQL Connection Manager (`YB_ENABLE_YSQL_CONN_MGR_IN_JAVA_TESTS=true`): ```bash ./yb_build.sh fastdebug --java-test org.yb.pgsql.TestPgRegressAuth ./yb_build.sh fastdebug --java-test org.yb.pgsql.TestPgPasswordValidity ./yb_build.sh fastdebug --java-test org.yb.pgsql.TestPgRegressPasswordHistory ./yb_build.sh fastdebug --java-test org.yb.pgsql.TestPgPasswordHistory ``` Manual: with 50d in ysql_pg_conf_csv, admin (own value 0) kept a session open while ysql_pg_conf_csv changed to 60d at runtime; admin's next reset in that session gave app_user 60 days.
1 parent ab8ab2b commit 89d65c2

11 files changed

Lines changed: 685 additions & 172 deletions

File tree

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
// Copyright (c) YugabyteDB, Inc.
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
4+
// in compliance with the License. You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software distributed under the License
9+
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
10+
// or implied. See the License for the specific language governing permissions and limitations
11+
// under the License.
12+
//
13+
package org.yb.pgsql;
14+
15+
import static org.yb.AssertionWrappers.assertEquals;
16+
17+
import java.nio.file.Files;
18+
import java.nio.file.Path;
19+
import java.nio.file.Paths;
20+
import java.sql.Connection;
21+
import java.sql.SQLException;
22+
import java.sql.Statement;
23+
import java.util.HashMap;
24+
import java.util.Map;
25+
import java.util.function.UnaryOperator;
26+
27+
import org.junit.Test;
28+
import org.junit.runner.RunWith;
29+
import org.yb.YBTestRunner;
30+
import org.yb.client.TestUtils;
31+
import org.yb.minicluster.MiniYBDaemon;
32+
33+
/**
34+
* yb_password_validity cases that need a value in the configuration file (ysql_pg_conf_csv). The
35+
* pg_regress test yb.orig.password_valid_until covers the rest; its cluster leaves the file value at
36+
* the default, 0.
37+
*/
38+
@RunWith(value = YBTestRunner.class)
39+
public class TestPgPasswordValidity extends BasePgSQLTest {
40+
private static final int FILE_VALIDITY_DAYS = 50;
41+
42+
@Override
43+
protected Map<String, String> getTServerFlags() {
44+
Map<String, String> flagMap = super.getTServerFlags();
45+
// The parameter is in minutes.
46+
appendToYsqlPgConf(flagMap, "yb_password_validity=" + FILE_VALIDITY_DAYS * 24 * 60);
47+
return flagMap;
48+
}
49+
50+
/**
51+
* A role without a setting of its own gets the file's value, both from a session that has the
52+
* file's value and from a session whose own setting replaced it. A role exempted by its own
53+
* setting gets no expiry.
54+
*/
55+
@Test
56+
public void testConfigFileValueForAnotherRole() throws Exception {
57+
try (Statement stmt = connection.createStatement()) {
58+
stmt.execute("CREATE ROLE pv_admin LOGIN CREATEROLE");
59+
stmt.execute("ALTER ROLE pv_admin SET yb_password_validity = 0");
60+
stmt.execute("CREATE ROLE pv_target LOGIN");
61+
stmt.execute("CREATE ROLE pv_exempt LOGIN VALID UNTIL 'infinity'");
62+
stmt.execute("ALTER ROLE pv_exempt SET yb_password_validity = 0");
63+
64+
assertEquals(FILE_VALIDITY_DAYS + "d", showValidity(stmt));
65+
stmt.execute("ALTER ROLE pv_target PASSWORD 'secret'");
66+
stmt.execute("ALTER ROLE pv_exempt PASSWORD 'secret'");
67+
assertEquals(FILE_VALIDITY_DAYS + " days", expiry(stmt, "pv_target"));
68+
assertEquals("infinity", expiry(stmt, "pv_exempt"));
69+
stmt.execute("ALTER ROLE pv_target VALID UNTIL 'infinity'");
70+
}
71+
72+
try (Connection admin = getConnectionBuilder().withUser("pv_admin").connect();
73+
Statement stmt = admin.createStatement()) {
74+
assertEquals("0", showValidity(stmt));
75+
stmt.execute("ALTER ROLE pv_target PASSWORD 'secret2'");
76+
stmt.execute("CREATE ROLE pv_created LOGIN PASSWORD 'secret'");
77+
}
78+
79+
try (Statement stmt = connection.createStatement()) {
80+
assertEquals(FILE_VALIDITY_DAYS + " days", expiry(stmt, "pv_target"));
81+
assertEquals(FILE_VALIDITY_DAYS + " days", expiry(stmt, "pv_created"));
82+
}
83+
}
84+
85+
/** ALTER ROLE ALL SET comes before the file's value for a role without a setting of its own. */
86+
@Test
87+
public void testAllRolesValueBeforeConfigFile() throws Exception {
88+
try (Statement stmt = connection.createStatement()) {
89+
stmt.execute("CREATE ROLE pv_all_target LOGIN");
90+
stmt.execute("ALTER ROLE ALL SET yb_password_validity = '30d'");
91+
try {
92+
stmt.execute("ALTER ROLE pv_all_target PASSWORD 'secret'");
93+
assertEquals("30 days", expiry(stmt, "pv_all_target"));
94+
} finally {
95+
stmt.execute("ALTER ROLE ALL RESET yb_password_validity");
96+
}
97+
}
98+
}
99+
100+
/**
101+
* After a reload, a role without a setting of its own gets the reloaded file's value, also from a
102+
* session that was open during the reload. An invalid value keeps the last valid one, and a file
103+
* without the setting gives the default, 0.
104+
*/
105+
@Test
106+
public void testConfigFileReload() throws Exception {
107+
try (Statement stmt = connection.createStatement()) {
108+
stmt.execute("CREATE ROLE pv_reload_admin LOGIN CREATEROLE");
109+
stmt.execute("ALTER ROLE pv_reload_admin SET yb_password_validity = 0");
110+
stmt.execute("CREATE ROLE pv_reload_target LOGIN");
111+
}
112+
113+
Map<Path, byte[]> saved = rewriteConfigFiles(text -> text + "yb_password_validity = '20d'\n");
114+
try (Connection admin = getConnectionBuilder().withUser("pv_reload_admin").connect();
115+
Statement adminStmt = admin.createStatement();
116+
Statement stmt = connection.createStatement()) {
117+
reloadConfigFiles();
118+
adminStmt.execute("ALTER ROLE pv_reload_target PASSWORD 'secret'");
119+
assertEquals("20 days", expiry(stmt, "pv_reload_target"));
120+
121+
rewriteConfigFiles(text -> text + "yb_password_validity = -1\n");
122+
reloadConfigFiles();
123+
stmt.execute("ALTER ROLE pv_reload_target VALID UNTIL 'infinity'");
124+
adminStmt.execute("ALTER ROLE pv_reload_target PASSWORD 'secret2'");
125+
assertEquals("20 days", expiry(stmt, "pv_reload_target"));
126+
127+
rewriteConfigFiles(text ->
128+
text.replaceAll("(?m)^[ \\t]*yb_password_validity[ \\t]*=.*\\n", ""));
129+
reloadConfigFiles();
130+
stmt.execute("ALTER ROLE pv_reload_target VALID UNTIL 'infinity'");
131+
adminStmt.execute("ALTER ROLE pv_reload_target PASSWORD 'secret3'");
132+
assertEquals("infinity", expiry(stmt, "pv_reload_target"));
133+
} finally {
134+
restoreConfigFiles(saved);
135+
reloadConfigFiles();
136+
}
137+
}
138+
139+
/** Rewrites each tserver's ysql_pg.conf with edit, and returns the original contents. */
140+
private Map<Path, byte[]> rewriteConfigFiles(UnaryOperator<String> edit) throws Exception {
141+
Map<Path, byte[]> saved = new HashMap<>();
142+
for (MiniYBDaemon ts : miniCluster.getTabletServers().values()) {
143+
Path conf = Paths.get(ts.getDataDirPath(), "pg_data", "ysql_pg.conf");
144+
byte[] contents = Files.readAllBytes(conf);
145+
saved.put(conf, contents);
146+
Files.write(conf, edit.apply(new String(contents)).getBytes());
147+
}
148+
return saved;
149+
}
150+
151+
private static void restoreConfigFiles(Map<Path, byte[]> saved) throws Exception {
152+
for (Map.Entry<Path, byte[]> entry : saved.entrySet()) {
153+
Files.write(entry.getKey(), entry.getValue());
154+
}
155+
}
156+
157+
/**
158+
* Reloads ysql_pg.conf on each tserver, then waits until new sessions there have the reloaded
159+
* file: pg_conf_load_time() changes when a reload applies the file.
160+
*/
161+
private void reloadConfigFiles() throws Exception {
162+
for (int i = 0; i < miniCluster.getTabletServers().size(); i++) {
163+
ConnectionBuilder builder = getConnectionBuilder().withTServer(i);
164+
String before;
165+
try (Connection conn = builder.connect(); Statement stmt = conn.createStatement()) {
166+
before = getSingleRow(stmt, "SELECT pg_conf_load_time()::text").getString(0);
167+
stmt.execute("SELECT pg_reload_conf()");
168+
}
169+
TestUtils.waitFor(() -> {
170+
try (Connection conn = builder.connect(); Statement stmt = conn.createStatement()) {
171+
return !before.equals(
172+
getSingleRow(stmt, "SELECT pg_conf_load_time()::text").getString(0));
173+
}
174+
}, 30000);
175+
}
176+
}
177+
178+
private static String showValidity(Statement stmt) throws SQLException {
179+
return getSingleRow(stmt, "SHOW yb_password_validity").getString(0);
180+
}
181+
182+
/**
183+
* Days until the role's password expires. The policy stamps the current time plus whole days,
184+
* so this rounds to that number.
185+
*/
186+
private static String expiry(Statement stmt, String role) throws SQLException {
187+
return getSingleRow(stmt,
188+
"SELECT CASE WHEN rolvaliduntil IS NULL THEN 'none'" +
189+
" WHEN isfinite(rolvaliduntil)" +
190+
" THEN round(extract(epoch FROM rolvaliduntil - now()) / 86400) || ' days'" +
191+
" ELSE rolvaliduntil::text END" +
192+
" FROM pg_authid WHERE rolname = '" + role + "'").getString(0);
193+
}
194+
}

0 commit comments

Comments
 (0)