Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/mandate-connections/src/token_entry.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! The vault's token entry for an Alpaca OAuth connection, format 1
//! ([DEC-2624](../../../docs/project/decisions/DEC-2624.md)): the bytes the token-exchange process
//! writes at `connections/{connection_id}/token` and the connection's executor reads through its
//! lease. They are exactly the canonical JSON (journal spec §4)
//! writes at `connections/x<hex>/token`, the connection id's hex after an `x`
//! ([DEC-2060](../../../docs/project/decisions/DEC-2060.md) item 3), and the connection's executor
//! reads through its lease. They are exactly the canonical JSON (journal spec §4)
//!
//! `{"access_token":"<token>","format":1,"scope":["data","trading"],"token_type":"bearer"}`
//!
Expand Down
13 changes: 3 additions & 10 deletions crates/mandate-vault/src/kube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use serde_json::json;

use crate::SourceError;
use crate::openbao::RoleCredentials;
use crate::policy::{Identity, role_name};
use crate::policy::{Identity, connection_hex, role_name};

/// What every Secret's name starts with, before the identity's role.
pub const SECRET_PREFIX: &str = "vault-approle-";
Expand Down Expand Up @@ -43,14 +43,7 @@ pub struct SecretManifest {
pub fn secret_name(identity: &Identity) -> Result<String, SourceError> {
let role = match identity {
Identity::TokenExchange(_) => return Err(SourceError::Config),
Identity::Executor(connection) => {
let hex: String = connection
.as_str()
.bytes()
.map(|byte| format!("{byte:02x}"))
.collect();
format!("executor-{hex}")
}
Identity::Executor(connection) => format!("executor-{}", connection_hex(connection)),
Identity::Api
| Identity::ConnectionManager
| Identity::Runtime
Expand All @@ -63,7 +56,7 @@ pub fn secret_name(identity: &Identity) -> Result<String, SourceError> {

/// Whether `namespace` is a Kubernetes label: 1 to 63 lowercase letters, digits and hyphens,
/// starting and ending with a letter or digit.
fn is_label(namespace: &str) -> bool {
pub(crate) fn is_label(namespace: &str) -> bool {
let alphanumeric = |byte: &u8| byte.is_ascii_lowercase() || byte.is_ascii_digit();
namespace.len() <= LABEL_MAX
&& namespace
Expand Down
241 changes: 241 additions & 0 deletions crates/mandate-vault/src/kubernetes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
//! Per-connection processes log in with OpenBao's Kubernetes auth (DEC-2060): each connection's
//! executor runs as the ServiceAccount named by the connection id's hex, and its token exchange as
//! that name after an `x`, both in the workspace's namespace, each kind on its own auth mount; one
//! templated policy per kind reads the path segment, `x` and the hex, from the login's own
//! ServiceAccount name, which the vault checks with TokenReview on every login. An executor's
//! name has an even number of hex digits and an exchange's an odd number of characters, so no
//! name is ever both. So no policy is ever written per connection, and the dedicated
//! provisioner (DEC-2605 row 23) needs no power over policies: it may only create, on connect,
//! one role per connection, bound to exactly that ServiceAccount in exactly that namespace, with
//! the one policy, audience and lifetimes pinned.

use serde_json::{Value, json};

use crate::SourceError;
use crate::kube::is_label;
use crate::lease::LEASE_SECS;
use crate::openbao::EXECUTOR_TOKEN_MAX_SECS;
use crate::policy::{
Identity, Mounts, SEGMENT_PREFIX, SecretPath, connection_hex, connection_segment, kv_path,
};
use crate::source::GRANT_SECS;

/// The parameters a role request must send, every one it sends, in the order the provisioner's
/// policy names them, so no parameter is left to the mount's default.
const REQUIRED: [&str; 8] = [
"alias_name_source",
"audience",
"bound_service_account_names",
"bound_service_account_namespaces",
"token_max_ttl",
"token_no_default_policy",
"token_policies",
"token_ttl",
];

/// One kind's place: its auth mount, its namespace, its policy, and its token's lifetimes.
struct Kind<'a> {
mount: &'a str,
namespace: &'a str,
policy: String,
ttl: i64,
max_ttl: i64,
}

/// Whether `segment` is one plain path segment: letters, digits, `_` and `-`, and not empty.
fn is_segment(segment: &str) -> bool {
!segment.is_empty()
&& segment
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// Refuses, [`SourceError::Config`], Kubernetes mounts that are not plain path segments or a
/// namespace that is not a Kubernetes label.
fn checked(mounts: &Mounts, namespace: &str) -> Result<(), SourceError> {
let plain = is_segment(&mounts.kubernetes_executor)
&& is_segment(&mounts.kubernetes_exchange)
&& is_label(namespace);
if plain {
Ok(())
} else {
Err(SourceError::Config)
}
}

/// The executor's place and the exchange's, in that order.
fn kinds<'a>(mounts: &'a Mounts, namespace: &'a str) -> [Kind<'a>; 2] {
[
Kind {
mount: &mounts.kubernetes_executor,
namespace,
policy: format!("{}-kubernetes-executor", mounts.kv),
ttl: LEASE_SECS,
max_ttl: EXECUTOR_TOKEN_MAX_SECS,
},
Kind {
mount: &mounts.kubernetes_exchange,
namespace,
policy: format!("{}-kubernetes-exchange", mounts.kv),
ttl: GRANT_SECS,
max_ttl: GRANT_SECS,
},
]
}

/// The audience every ServiceAccount token a process logs in with is projected for, so a token
/// the cluster's API server accepts is not one the vault accepts.
pub const AUDIENCE: &str = "mandate-vault";

/// The ServiceAccount a connection's executor or token exchange runs as: the connection id's
/// bytes in lowercase hexadecimal, after an `x` for the exchange, a valid Kubernetes name for
/// every id. The exchange's name is the path segment both kinds' policies reach.
pub fn service_account_name(identity: &Identity) -> Result<String, SourceError> {
match identity {
Identity::Executor(connection) => Ok(connection_hex(connection)),
Identity::TokenExchange(connection) => connection_segment(connection),
Identity::Api
| Identity::ConnectionManager
| Identity::Runtime
| Identity::SecretImport
| Identity::ModelGateway
| Identity::EmailSender => Err(SourceError::Config),
}
}

/// The name of the templated policy of `identity`'s kind under `mounts`.
pub fn kubernetes_policy_name(identity: &Identity, mounts: &Mounts) -> Result<String, SourceError> {
match identity {
Identity::Executor(_) => Ok(format!("{}-kubernetes-executor", mounts.kv)),
Identity::TokenExchange(_) => Ok(format!("{}-kubernetes-exchange", mounts.kv)),
Identity::Api
| Identity::ConnectionManager
| Identity::Runtime
| Identity::SecretImport
| Identity::ModelGateway
| Identity::EmailSender => Err(SourceError::Config),
}
}

/// The templated policy, in HCL, of `identity`'s kind, keyed by the ServiceAccount name in the
/// login's alias metadata on the auth mount whose accessor is `accessor`, an `x` before an
/// executor's, so both kinds reach [`crate::policy::connection_segment`]. An executor reads its
/// connection's token; a token exchange writes it, reads and deletes its code, and reads the
/// platform's client secret. Anything else, or an accessor that is not one plain path segment (a
/// quote, a brace or a newline would end the template or the policy), is [`SourceError::Config`].
pub fn kubernetes_policy(
identity: &Identity,
mounts: &Mounts,
accessor: &str,
) -> Result<String, SourceError> {
if !is_segment(accessor) {
return Err(SourceError::Config);
}
let own = format!("{{{{identity.entity.aliases.{accessor}.metadata.service_account_name}}}}");
let block = |prefix: &str, path: &str, capabilities: &str| {
format!(
"path \"{}/{prefix}/{path}\" {{\n capabilities = [{capabilities}]\n}}\n",
mounts.kv
)
};
match identity {
Identity::Executor(_) => Ok(block(
"data",
&format!("connections/{SEGMENT_PREFIX}{own}/token"),
"\"read\"",
)),
Identity::TokenExchange(_) => Ok([
block("data", &kv_path(&SecretPath::ClientSecret)?, "\"read\""),
block("data", &format!("connections/{own}/code"), "\"read\""),
block("metadata", &format!("connections/{own}/code"), "\"delete\""),
block(
"data",
&format!("connections/{own}/token"),
"\"create\", \"update\"",
),
]
.concat()),
Identity::Api
| Identity::ConnectionManager
| Identity::Runtime
| Identity::SecretImport
| Identity::ModelGateway
| Identity::EmailSender => Err(SourceError::Config),
}
}

/// The provisioner's policy, in HCL: it may create, update and read roles on the two Kubernetes
/// auth mounts and nothing else, every parameter but the ServiceAccount's name pinned to its one
/// value, so it can neither widen a role's namespace, policy, audience or lifetime nor reach a
/// policy, a token or a secret. Both kinds' ServiceAccounts are in `namespace`, the workspace's
/// own, so its default deny, egress policies and admission rules cover them. Kubernetes mounts
/// that are not one plain path segment, or a namespace that is not a Kubernetes label, are
/// [`SourceError::Config`].
pub fn provisioner_policy(mounts: &Mounts, namespace: &str) -> Result<String, SourceError> {
checked(mounts, namespace)?;
let required: Vec<String> = REQUIRED.iter().map(|name| format!("\"{name}\"")).collect();
Ok(kinds(mounts, namespace)
.iter()
.map(|kind| {
format!(
"path \"auth/{mount}/role/+\" {{\n \
capabilities = [\"create\", \"update\", \"read\"]\n \
required_parameters = [{required}]\n \
allowed_parameters = {{\n \
\"alias_name_source\" = [\"serviceaccount_uid\"]\n \
\"audience\" = [\"{AUDIENCE}\"]\n \
\"bound_service_account_names\" = []\n \
\"bound_service_account_namespaces\" = [\"{namespace}\"]\n \
\"token_max_ttl\" = [\"{max_ttl}\"]\n \
\"token_no_default_policy\" = [\"false\"]\n \
\"token_policies\" = [\"{policy}\"]\n \
\"token_ttl\" = [\"{ttl}\"]\n \
}}\n}}\n",
mount = kind.mount,
required = required.join(", "),
namespace = kind.namespace,
max_ttl = kind.max_ttl,
policy = kind.policy,
ttl = kind.ttl,
)
})
.collect())
}

/// The request that makes `identity`'s role: its path, `auth/<mount>/role/<name>`, the role named
/// by its ServiceAccount, since OpenBao folds role names to lowercase and two ids differing in case
/// would otherwise share one, and its body, bound to exactly its ServiceAccount in exactly `namespace`, the workspace's. Anything
/// but an executor or a token exchange, or mounts or a namespace [`provisioner_policy`] refuses, is
/// [`SourceError::Config`].
pub fn role_request(
identity: &Identity,
mounts: &Mounts,
namespace: &str,
) -> Result<(String, Value), SourceError> {
checked(mounts, namespace)?;
let [executor, exchange] = kinds(mounts, namespace);
let kind = match identity {
Identity::Executor(_) => executor,
Identity::TokenExchange(_) => exchange,
Identity::Api
| Identity::ConnectionManager
| Identity::Runtime
| Identity::SecretImport
| Identity::ModelGateway
| Identity::EmailSender => return Err(SourceError::Config),
};
let name = service_account_name(identity)?;
Ok((
format!("auth/{}/role/{name}", kind.mount),
json!({
"bound_service_account_names": [name],
"bound_service_account_namespaces": [kind.namespace],
"audience": AUDIENCE,
"alias_name_source": "serviceaccount_uid",
"token_policies": [kind.policy],
"token_ttl": kind.ttl.to_string(),
"token_max_ttl": kind.max_ttl.to_string(),
"token_no_default_policy": "false"
}),
))
}
1 change: 1 addition & 0 deletions crates/mandate-vault/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
pub mod credentials;
pub mod error;
pub mod kube;
pub mod kubernetes;
pub mod lease;
pub mod local;
pub mod mounted;
Expand Down
2 changes: 1 addition & 1 deletion crates/mandate-vault/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ impl LocalSource {
KeyRef::new(ALPACA_CLIENT_SECRET_KEY_REF).map_err(|_| SourceError::Config)?,
),
SecretPath::Platform(_) => {
Entry::client_secret(KeyRef::new(&kv_path(path)).map_err(|_| SourceError::Config)?)
Entry::client_secret(KeyRef::new(&kv_path(path)?).map_err(|_| SourceError::Config)?)
}
})
}
Expand Down
14 changes: 7 additions & 7 deletions crates/mandate-vault/src/openbao.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ use crate::source::{GRANT_SECS, Grant, SecretSource};
/// How long one request may take before the vault counts as unreachable.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// The longest an executor's token lives through renewals before it logs in again: 30 days.
const EXECUTOR_TOKEN_MAX_SECS: i64 = 2_592_000;
pub(crate) const EXECUTOR_TOKEN_MAX_SECS: i64 = 2_592_000;
/// Whether this build may use a dev server: only this crate's own unit-test build, so no other
/// crate's build, test or not, can turn it on (DEC-977 item 6).
const ALLOW_DEV_SERVER: bool = cfg!(test);
Expand Down Expand Up @@ -307,8 +307,8 @@ impl OpenBaoSource {
self.http.call(method, path, Some(&self.token), body).await
}

fn data_path(&self, path: &SecretPath) -> String {
format!("{}/data/{}", self.mounts.kv, kv_path(path))
fn data_path(&self, path: &SecretPath) -> Result<String, SourceError> {
Ok(format!("{}/data/{}", self.mounts.kv, kv_path(path)?))
}

fn token_expiry(&self) -> Result<UtcNanos, SourceError> {
Expand All @@ -325,7 +325,7 @@ impl OpenBaoSource {
}

async fn read_value(&self, path: &SecretPath) -> Result<Option<SecretSlice<u8>>, SourceError> {
let value = match self.call(Method::GET, &self.data_path(path), None).await {
let value = match self.call(Method::GET, &self.data_path(path)?, None).await {
Ok(value) => value,
Err(SourceError::Missing) => return Ok(None),
Err(e) => return Err(e),
Expand Down Expand Up @@ -355,7 +355,7 @@ impl SecretSource for OpenBaoSource {
let mut encoded = STANDARD.encode(secret.expose_secret());
let body = json!({ "data": { "value": encoded } });
encoded.zeroize();
self.call(Method::POST, &self.data_path(path), Some(&body))
self.call(Method::POST, &self.data_path(path)?, Some(&body))
.await
.map(drop)
}
Expand All @@ -365,7 +365,7 @@ impl SecretSource for OpenBaoSource {
}

async fn delete(&self, path: &SecretPath) -> Result<(), SourceError> {
let metadata = format!("{}/metadata/{}", self.mounts.kv, kv_path(path));
let metadata = format!("{}/metadata/{}", self.mounts.kv, kv_path(path)?);
match self.call(Method::DELETE, &metadata, None).await {
Ok(_) | Err(SourceError::Missing) => Ok(()),
Err(e) => Err(e),
Expand Down Expand Up @@ -565,7 +565,7 @@ pub async fn provision(
let mut credentials = Vec::new();
for identity in provisioned_identities(connections) {
let policy = policy_name(&identity, mounts);
let hcl = openbao_policy(&identity, connections, mounts);
let hcl = openbao_policy(&identity, connections, mounts)?;
http.call(
Method::PUT,
&format!("sys/policies/acl/{policy}"),
Expand Down
Loading
Loading