Skip to content

Commit d66d338

Browse files
authored
feat(server): authenticate postgres with azure workload identity (#5635)
* feat(server): authenticate postgres with azure workload identity Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * docs(gateway): clarify azure postgres schema grants Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * fix(server): reuse busy postgres sessions during entra outages Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * docs(server): clarify idle-session polling Signed-off-by: Taylor Mutch <taylormutch@gmail.com> * fix(postgres): preserve transport timeout error classification Signed-off-by: Taylor Mutch <taylormutch@gmail.com> --------- Signed-off-by: Taylor Mutch <taylormutch@gmail.com>
1 parent 3231897 commit d66d338

12 files changed

Lines changed: 1211 additions & 19 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/openshell-core/src/config.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,35 @@ use std::path::PathBuf;
1313
use std::str::FromStr;
1414
use std::time::Duration;
1515

16+
/// Database credential source. The default preserves URL/SQLite behavior.
17+
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
18+
#[serde(rename_all = "kebab-case")]
19+
pub enum DatabaseAuthMode {
20+
#[default]
21+
Default,
22+
AzureWorkloadIdentity,
23+
}
24+
25+
impl fmt::Display for DatabaseAuthMode {
26+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27+
f.write_str(match self {
28+
Self::Default => "default",
29+
Self::AzureWorkloadIdentity => "azure-workload-identity",
30+
})
31+
}
32+
}
33+
34+
impl FromStr for DatabaseAuthMode {
35+
type Err = &'static str;
36+
fn from_str(value: &str) -> Result<Self, Self::Err> {
37+
match value {
38+
"default" => Ok(Self::Default),
39+
"azure-workload-identity" => Ok(Self::AzureWorkloadIdentity),
40+
_ => Err("database authentication must be default or azure-workload-identity"),
41+
}
42+
}
43+
}
44+
1645
// ── Public default constants ────────────────────────────────────────────
1746
//
1847
// Canonical source for default values used across multiple crates.
@@ -301,6 +330,9 @@ pub struct Config {
301330
/// Database URL for persistence.
302331
pub database_url: String,
303332

333+
/// Explicit database identity mode; independent of provider credentials.
334+
pub database_auth: DatabaseAuthMode,
335+
304336
/// Connection ceiling for the persistence pool.
305337
///
306338
/// `None` leaves the backend's built-in default in place. The right
@@ -1084,6 +1116,7 @@ impl Config {
10841116
mtls_auth: MtlsAuthConfig::default(),
10851117
gateway_jwt: None,
10861118
database_url: String::new(),
1119+
database_auth: DatabaseAuthMode::default(),
10871120
database_max_connections: None,
10881121
database_lock_max_connections: None,
10891122
compute_driver: None,
@@ -1144,6 +1177,13 @@ impl Config {
11441177
self
11451178
}
11461179

1180+
/// Select database credentials independently of the connection URL.
1181+
#[must_use]
1182+
pub fn with_database_auth(mut self, mode: DatabaseAuthMode) -> Self {
1183+
self.database_auth = mode;
1184+
self
1185+
}
1186+
11471187
/// Create a new configuration with a database URL.
11481188
#[must_use]
11491189
pub fn with_database_url(mut self, url: impl Into<String>) -> Self {

‎crates/openshell-server/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ sha2 = { workspace = true }
9999
jsonwebtoken = { workspace = true }
100100
spiffe = { workspace = true }
101101
async-trait = "0.1"
102+
async-stream = "0.3"
102103
url = { workspace = true }
103104
glob = { workspace = true }
104105
hex = "0.4"

‎crates/openshell-server/src/cli.rs‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,10 @@ struct RunArgs {
154154
#[arg(long, env = "OPENSHELL_DB_URL")]
155155
db_url: Option<String>,
156156

157+
/// Database identity source: default or azure-workload-identity.
158+
#[arg(long, env = "OPENSHELL_DB_AUTH")]
159+
db_auth: Option<openshell_core::config::DatabaseAuthMode>,
160+
157161
/// Connection ceiling for the database pool, shared by every
158162
/// database-backed request.
159163
///
@@ -629,6 +633,7 @@ fn prepare_server_config_with_drivers(
629633

630634
config = config
631635
.with_database_url(db_url)
636+
.with_database_auth(args.db_auth.unwrap_or_default())
632637
.with_database_max_connections(args.db_max_connections)
633638
.with_database_lock_max_connections(args.db_lock_max_connections);
634639
if let Some(driver) = &args.compute_driver {
@@ -1698,6 +1703,12 @@ fn merge_file_into_args(args: &mut RunArgs, file: &GatewayFileSection, matches:
16981703
{
16991704
args.grpc_rate_limit_window_seconds = Some(window);
17001705
}
1706+
if let Some(mode) = file.database_auth
1707+
&& args.db_auth.is_none()
1708+
&& arg_defaulted(matches, "db_auth")
1709+
{
1710+
args.db_auth = Some(mode);
1711+
}
17011712
if let Some(max_connections) = file.database_max_connections
17021713
&& args.db_max_connections.is_none()
17031714
&& arg_defaulted(matches, "db_max_connections")
@@ -1801,7 +1812,7 @@ mod tests {
18011812
use super::{Cli, command};
18021813
use crate::test_environment::Environment;
18031814
use clap::Parser;
1804-
use openshell_core::config::ServiceHostnameFormat;
1815+
use openshell_core::config::{DatabaseAuthMode, ServiceHostnameFormat};
18051816
use std::net::{IpAddr, Ipv4Addr};
18061817
use std::sync::atomic::{AtomicUsize, Ordering};
18071818

@@ -4468,6 +4479,33 @@ grpc_rate_limit_window_seconds = 30
44684479
assert_eq!(args.grpc_rate_limit_window_seconds, Some(30));
44694480
}
44704481

4482+
#[test]
4483+
fn database_auth_file_and_explicit_overrides() {
4484+
Environment::new().remove("OPENSHELL_DB_AUTH").run(|| {
4485+
let file = config_file_from_toml(
4486+
"[openshell.gateway]\ndatabase_auth = \"azure-workload-identity\"\n",
4487+
);
4488+
let (mut args, matches) = parse_with_args(&["openshell-gateway"]);
4489+
assert_eq!(args.db_auth, None);
4490+
merge_file_into_args(&mut args, &file.openshell.gateway, &matches);
4491+
assert_eq!(args.db_auth, Some(DatabaseAuthMode::AzureWorkloadIdentity));
4492+
let (mut args, matches) =
4493+
parse_with_args(&["openshell-gateway", "--db-auth", "default"]);
4494+
merge_file_into_args(&mut args, &file.openshell.gateway, &matches);
4495+
assert_eq!(args.db_auth, Some(DatabaseAuthMode::Default));
4496+
});
4497+
Environment::new()
4498+
.set("OPENSHELL_DB_AUTH", "default")
4499+
.run(|| {
4500+
let file = config_file_from_toml(
4501+
"[openshell.gateway]\ndatabase_auth = \"azure-workload-identity\"\n",
4502+
);
4503+
let (mut args, matches) = parse_with_args(&["openshell-gateway"]);
4504+
merge_file_into_args(&mut args, &file.openshell.gateway, &matches);
4505+
assert_eq!(args.db_auth, Some(DatabaseAuthMode::Default));
4506+
});
4507+
}
4508+
44714509
#[test]
44724510
fn file_db_max_connections_populates_args_when_cli_omits() {
44734511
Environment::new()

‎crates/openshell-server/src/config_file.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ pub struct GatewayFileSection {
111111
pub log_level: Option<String>,
112112

113113
// ── Database ─────────────────────────────────────────────────────────
114+
/// Explicit identity source; connection URL stays environment-only.
115+
#[serde(default)]
116+
pub database_auth: Option<openshell_core::config::DatabaseAuthMode>,
114117
/// Connection ceiling for the persistence pool. One shared pool serves
115118
/// every database-backed RPC, so this is also the gateway's ceiling on
116119
/// concurrent database work. On Postgres, each replica also opens up to

‎crates/openshell-server/src/lib.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1637,10 +1637,11 @@ async fn connect_store(
16371637
let mut delay = DATABASE_CONNECT_RETRY_INITIAL_DELAY;
16381638
let mut waiting = false;
16391639
loop {
1640-
let attempt = Store::try_connect_with_pool_sizes(
1640+
let attempt = Store::try_connect_with_database_auth(
16411641
database_url,
16421642
config.database_max_connections,
16431643
config.database_lock_max_connections,
1644+
config.database_auth,
16441645
);
16451646
let result = if waiting {
16461647
tokio::select! {

0 commit comments

Comments
 (0)