Skip to content

Commit 7e8ce1a

Browse files
committed
feat(server): persist warm-pool claim-to-sandbox mappings
Add a durable, HA-safe (namespace, claim_name, claim_uid) -> sandbox_id mapping in the shared object store, keyed so a uid mismatch fails closed and rebinding an existing key to a different sandbox id is rejected. This is the record the warm-pool identity re-anchor resolves against. Signed-off-by: Roshni Malani <rmalani@nvidia.com>
1 parent 672ee5c commit 7e8ce1a

2 files changed

Lines changed: 270 additions & 0 deletions

File tree

‎crates/openshell-server/src/persistence/mod.rs‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ pub use sqlite::SqliteStore;
2323
pub const POLICY_OBJECT_TYPE: &str = "sandbox_policy";
2424
/// Object type string for draft policy chunk records.
2525
pub const DRAFT_CHUNK_OBJECT_TYPE: &str = "draft_policy_chunk";
26+
/// Object type string for warm-pool `SandboxClaim` → sandbox-id mappings.
27+
///
28+
/// Stored in the shared `objects` table so any HA gateway replica can serve the
29+
/// `IssueSandboxToken` bootstrap. The record `id` is keyed on
30+
/// `(namespace, claim_name, claim_uid)` (so a lookup miss on a uid mismatch
31+
/// fails closed) and the record `name` is the sandbox-id (so a sandbox can be
32+
/// torn down by id without re-deriving the claim key).
33+
pub const CLAIM_MAPPING_OBJECT_TYPE: &str = "k8s_claim_mapping";
2634

2735
pub type PersistenceResult<T> = Result<T, PersistenceError>;
2836

@@ -507,6 +515,130 @@ impl Store {
507515
updated.set_resource_version(result.resource_version);
508516
Ok(updated)
509517
}
518+
519+
// -----------------------------------------------------------------------
520+
// Warm-pool claim mappings
521+
// -----------------------------------------------------------------------
522+
523+
/// Persist a durable `(namespace, claim_name, claim_uid) -> sandbox_id`
524+
/// mapping for a gateway-created warm-pool `SandboxClaim`.
525+
///
526+
/// Idempotent: a re-write of the identical mapping (same key + same
527+
/// sandbox-id) is accepted so create, bootstrap, and reconcile back-fill
528+
/// retries converge. A write that would rebind an existing claim key to a
529+
/// *different* sandbox-id is rejected — that must never happen because the
530+
/// claim UID is apiserver-assigned and unique.
531+
pub async fn put_claim_mapping(&self, mapping: &ClaimMapping) -> PersistenceResult<()> {
532+
let id = claim_mapping_id(&mapping.namespace, &mapping.claim_name, &mapping.claim_uid);
533+
534+
if let Some(existing) = self.get_claim_mapping_by_id(&id).await? {
535+
return if existing.sandbox_id == mapping.sandbox_id {
536+
Ok(())
537+
} else {
538+
Err(claim_mapping_rebind_error(&id))
539+
};
540+
}
541+
542+
let payload = serde_json::to_vec(mapping)
543+
.map_err(|e| PersistenceError::Encode(format!("claim mapping encode error: {e}")))?;
544+
545+
match self
546+
.put_if(
547+
CLAIM_MAPPING_OBJECT_TYPE,
548+
&id,
549+
&mapping.sandbox_id,
550+
&payload,
551+
None,
552+
WriteCondition::MustCreate,
553+
)
554+
.await
555+
{
556+
Ok(_) => Ok(()),
557+
// Lost a concurrent MustCreate race: accept iff the winner stored
558+
// the same binding, otherwise surface the conflict.
559+
Err(PersistenceError::UniqueViolation { .. }) => {
560+
match self.get_claim_mapping_by_id(&id).await? {
561+
Some(existing) if existing.sandbox_id == mapping.sandbox_id => Ok(()),
562+
_ => Err(claim_mapping_rebind_error(&id)),
563+
}
564+
}
565+
Err(e) => Err(e),
566+
}
567+
}
568+
569+
/// Look up the sandbox-id bound to a warm-pool claim. A miss (including a
570+
/// `claim_uid` that does not match a stored record) returns `Ok(None)` so
571+
/// callers fail closed.
572+
pub async fn get_claim_mapping(
573+
&self,
574+
namespace: &str,
575+
claim_name: &str,
576+
claim_uid: &str,
577+
) -> PersistenceResult<Option<ClaimMapping>> {
578+
self.get_claim_mapping_by_id(&claim_mapping_id(namespace, claim_name, claim_uid))
579+
.await
580+
}
581+
582+
async fn get_claim_mapping_by_id(&self, id: &str) -> PersistenceResult<Option<ClaimMapping>> {
583+
let Some(record) = self.get(CLAIM_MAPPING_OBJECT_TYPE, id).await? else {
584+
return Ok(None);
585+
};
586+
let mapping: ClaimMapping = serde_json::from_slice(&record.payload)
587+
.map_err(|e| PersistenceError::Decode(format!("claim mapping decode error: {e}")))?;
588+
Ok(Some(mapping))
589+
}
590+
591+
/// Delete a warm-pool claim mapping by its sandbox-id (the record name).
592+
/// Returns `true` when a mapping was removed.
593+
pub async fn delete_claim_mapping_for_sandbox(
594+
&self,
595+
sandbox_id: &str,
596+
) -> PersistenceResult<bool> {
597+
self.delete_by_name(CLAIM_MAPPING_OBJECT_TYPE, sandbox_id)
598+
.await
599+
}
600+
601+
/// List all warm-pool claim mappings (used by reconcile GC). Bounded by
602+
/// `limit`/`offset`.
603+
pub async fn list_claim_mappings(
604+
&self,
605+
limit: u32,
606+
offset: u32,
607+
) -> PersistenceResult<Vec<ClaimMapping>> {
608+
let records = self.list(CLAIM_MAPPING_OBJECT_TYPE, limit, offset).await?;
609+
let mut mappings = Vec::with_capacity(records.len());
610+
for record in records {
611+
let mapping: ClaimMapping = serde_json::from_slice(&record.payload).map_err(|e| {
612+
PersistenceError::Decode(format!("claim mapping decode error: {e}"))
613+
})?;
614+
mappings.push(mapping);
615+
}
616+
Ok(mappings)
617+
}
618+
}
619+
620+
/// Durable mapping that binds a gateway-created warm-pool `SandboxClaim` to the
621+
/// sandbox identity the gateway assigned. The auth bootstrap re-anchors a warm
622+
/// sandbox pod's identity to this record (see `auth::k8s_sa`).
623+
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
624+
pub struct ClaimMapping {
625+
pub namespace: String,
626+
pub claim_name: String,
627+
pub claim_uid: String,
628+
pub sandbox_id: String,
629+
}
630+
631+
fn claim_mapping_id(namespace: &str, claim_name: &str, claim_uid: &str) -> String {
632+
format!("{namespace}/{claim_name}/{claim_uid}")
633+
}
634+
635+
fn claim_mapping_rebind_error(id: &str) -> PersistenceError {
636+
PersistenceError::unique_violation(
637+
Some(CLAIM_MAPPING_OBJECT_TYPE.to_string()),
638+
Some(format!(
639+
"claim mapping {id} is already bound to a different sandbox"
640+
)),
641+
)
510642
}
511643

512644
pub fn current_time_ms() -> i64 {

‎crates/openshell-server/src/persistence/tests.rs‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,3 +1335,141 @@ async fn cas_update_message_cas_conflicts_on_concurrent_updates() {
13351335
"resource_version should be 2 (initial 1 + 1 successful update)"
13361336
);
13371337
}
1338+
1339+
// ---------------------------------------------------------------------------
1340+
// Warm-pool claim mappings
1341+
// ---------------------------------------------------------------------------
1342+
1343+
use super::ClaimMapping;
1344+
1345+
fn claim_mapping(ns: &str, name: &str, uid: &str, sandbox_id: &str) -> ClaimMapping {
1346+
ClaimMapping {
1347+
namespace: ns.to_string(),
1348+
claim_name: name.to_string(),
1349+
claim_uid: uid.to_string(),
1350+
sandbox_id: sandbox_id.to_string(),
1351+
}
1352+
}
1353+
1354+
#[tokio::test]
1355+
async fn claim_mapping_put_get_round_trip() {
1356+
let store = test_store().await;
1357+
let mapping = claim_mapping("openshell", "claim-a", "uid-a", "sandbox-a");
1358+
store.put_claim_mapping(&mapping).await.unwrap();
1359+
1360+
let fetched = store
1361+
.get_claim_mapping("openshell", "claim-a", "uid-a")
1362+
.await
1363+
.unwrap()
1364+
.expect("mapping should exist");
1365+
assert_eq!(fetched, mapping);
1366+
}
1367+
1368+
#[tokio::test]
1369+
async fn claim_mapping_lookup_misses_on_uid_mismatch() {
1370+
let store = test_store().await;
1371+
store
1372+
.put_claim_mapping(&claim_mapping("openshell", "claim-a", "uid-a", "sandbox-a"))
1373+
.await
1374+
.unwrap();
1375+
1376+
// Same namespace + claim name but a different UID must not resolve: this is
1377+
// the fail-closed leg of the identity re-anchor chain.
1378+
let miss = store
1379+
.get_claim_mapping("openshell", "claim-a", "uid-b")
1380+
.await
1381+
.unwrap();
1382+
assert!(miss.is_none(), "uid mismatch must not resolve a mapping");
1383+
1384+
// A different namespace must not resolve either (cross-namespace pinning).
1385+
let miss_ns = store
1386+
.get_claim_mapping("other", "claim-a", "uid-a")
1387+
.await
1388+
.unwrap();
1389+
assert!(miss_ns.is_none(), "namespace mismatch must not resolve");
1390+
}
1391+
1392+
#[tokio::test]
1393+
async fn claim_mapping_put_is_idempotent_for_identical_record() {
1394+
let store = test_store().await;
1395+
let mapping = claim_mapping("openshell", "claim-a", "uid-a", "sandbox-a");
1396+
store.put_claim_mapping(&mapping).await.unwrap();
1397+
// A re-write of the identical mapping (bootstrap/reconcile retry) succeeds.
1398+
store
1399+
.put_claim_mapping(&mapping)
1400+
.await
1401+
.expect("identical re-write should be idempotent");
1402+
}
1403+
1404+
#[tokio::test]
1405+
async fn claim_mapping_put_rejects_rebind_to_other_sandbox() {
1406+
let store = test_store().await;
1407+
store
1408+
.put_claim_mapping(&claim_mapping("openshell", "claim-a", "uid-a", "sandbox-a"))
1409+
.await
1410+
.unwrap();
1411+
1412+
// The same claim key must never be rebound to a different sandbox-id.
1413+
let err = store
1414+
.put_claim_mapping(&claim_mapping("openshell", "claim-a", "uid-a", "sandbox-b"))
1415+
.await
1416+
.expect_err("rebind to a different sandbox must be rejected");
1417+
assert!(matches!(err, PersistenceError::UniqueViolation { .. }));
1418+
1419+
// The original binding is unchanged.
1420+
let fetched = store
1421+
.get_claim_mapping("openshell", "claim-a", "uid-a")
1422+
.await
1423+
.unwrap()
1424+
.unwrap();
1425+
assert_eq!(fetched.sandbox_id, "sandbox-a");
1426+
}
1427+
1428+
#[tokio::test]
1429+
async fn claim_mapping_delete_by_sandbox_id() {
1430+
let store = test_store().await;
1431+
store
1432+
.put_claim_mapping(&claim_mapping("openshell", "claim-a", "uid-a", "sandbox-a"))
1433+
.await
1434+
.unwrap();
1435+
1436+
let deleted = store
1437+
.delete_claim_mapping_for_sandbox("sandbox-a")
1438+
.await
1439+
.unwrap();
1440+
assert!(deleted, "delete should report removal");
1441+
assert!(
1442+
store
1443+
.get_claim_mapping("openshell", "claim-a", "uid-a")
1444+
.await
1445+
.unwrap()
1446+
.is_none(),
1447+
"mapping must be gone after delete"
1448+
);
1449+
1450+
// Deleting an unknown sandbox-id is a no-op, not an error.
1451+
let missing = store
1452+
.delete_claim_mapping_for_sandbox("sandbox-zzz")
1453+
.await
1454+
.unwrap();
1455+
assert!(!missing, "deleting an unknown mapping returns false");
1456+
}
1457+
1458+
#[tokio::test]
1459+
async fn claim_mapping_list_returns_all() {
1460+
let store = test_store().await;
1461+
store
1462+
.put_claim_mapping(&claim_mapping("openshell", "claim-a", "uid-a", "sandbox-a"))
1463+
.await
1464+
.unwrap();
1465+
store
1466+
.put_claim_mapping(&claim_mapping("openshell", "claim-b", "uid-b", "sandbox-b"))
1467+
.await
1468+
.unwrap();
1469+
1470+
let mut mappings = store.list_claim_mappings(100, 0).await.unwrap();
1471+
mappings.sort_by(|a, b| a.sandbox_id.cmp(&b.sandbox_id));
1472+
assert_eq!(mappings.len(), 2);
1473+
assert_eq!(mappings[0].sandbox_id, "sandbox-a");
1474+
assert_eq!(mappings[1].sandbox_id, "sandbox-b");
1475+
}

0 commit comments

Comments
 (0)