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
15 changes: 15 additions & 0 deletions scripts/codegen/sdk_rust_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,18 @@ def operation_facts() -> str:
return "\n".join(facts)


def namespace_hint_exclusions() -> str:
from server.operations.registry import ALL_OPERATIONS

names = [
op.name
for op in ALL_OPERATIONS
if (op.skip_namespace_authz or op.deployment_scoped or op.row_scoped)
and "namespace" in operation_identity_fields(op)[0]
]
return "\n".join(f"{rust_string(name)}," for name in sorted(names))


def selected_operations(selected: tuple[str, ...] | None = None) -> list[Any]:
from server.operations.registry import ALL_OPERATIONS

Expand Down Expand Up @@ -781,6 +793,9 @@ def build(selected: tuple[str, ...] | None = None) -> str:
+ "\npub(crate) const OP_POLICIES: &[OperationPolicy] = &[\n"
+ operation_facts()
+ "\n];\n"
+ "\npub(crate) const NAMESPACE_HINT_EXCLUSIONS: &[&str] = &[\n"
+ namespace_hint_exclusions()
+ "\n];\n"
+ "\n\n".join(em.declarations.values())
+ "\n"
+ "\n".join(em.defaults)
Expand Down
2 changes: 2 additions & 0 deletions sdk/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ name = "blocking"
required-features = ["blocking"]

[dependencies]
base64 = "0.22"
reqwest = { version = "0.12.28", default-features = false, features = [
"json",
"rustls-tls",
Expand All @@ -30,6 +31,7 @@ derive_more = { version = "2", features = ["display"] }
log = "0.4"
httpdate = "1"
tokio = { version = "1", features = ["sync", "time"] }
unicode-general-category = "0.6"

[dev-dependencies]
sha2 = "0.10"
Expand Down
65 changes: 61 additions & 4 deletions sdk/rust/src/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ use serde::{de::DeserializeOwned, Serialize};
use tokio::sync::mpsc;

use crate::{
CallFailure, CallOptions, CallResult, Error, RetryPolicy, RouteRequest, RouteResponse,
CallFailure, CallOptions, CallResult, Capabilities, Error, RetryPolicy, RouteRequest,
RouteResponse, TokenClaims,
};

type Job = Box<dyn FnOnce(crate::Client) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send>;
Expand All @@ -34,6 +35,7 @@ impl Drop for Worker {
pub struct Client {
worker: Arc<Worker>,
retry: Option<RetryPolicy>,
claims: Option<Arc<TokenClaims>>,
}

/// Endpoint, identity and retry settings for a synchronous client.
Expand Down Expand Up @@ -126,6 +128,43 @@ impl Client {
})
}

/// The deployment's served operations with this token's claims; see
/// [`crate::Client::permissions`].
pub fn permissions(&self, max_age: Duration) -> Result<Capabilities, Error> {
self.onboarding(move |client| async move { client.permissions(max_age).await })
}

/// Whether this client's token may call `op`; see [`crate::Client::can_call`].
pub fn can_call(&self, op: &str) -> Result<Option<bool>, Error> {
let op = op.to_owned();
self.onboarding(|client| async move { client.can_call(&op).await })
}

/// The unverified bearer token payload; see [`crate::Client::token_claims`].
pub fn token_claims(&self) -> Option<&TokenClaims> {
self.claims.as_deref()
}

/// How to use Loom, as Markdown; see [`crate::Client::guide`].
pub fn guide(&self, part: crate::MentorGuideInputPart) -> Result<String, Error> {
self.onboarding(move |client| async move { client.guide(part).await })
}

/// The store's advice to this agent; see [`crate::Client::mentor`].
pub fn mentor(&self) -> Result<crate::MentorBriefOutput, Error> {
self.onboarding(|client| async move { client.mentor().await })
}

/// See [`crate::Client::mentor_with_window`]; the response reports the window used.
pub fn mentor_with_window(
&self,
window_seconds: i64,
) -> Result<crate::MentorBriefOutput, Error> {
self.onboarding(
move |client| async move { client.mentor_with_window(window_seconds).await },
)
}

pub fn get_with_options(
&self,
memory_key: &str,
Expand Down Expand Up @@ -245,6 +284,22 @@ impl Client {
.map_err(|_| worker_error())?;
receiver.recv().map_err(|_| worker_error())?
}

fn onboarding<T: Send + 'static, F, Fut>(&self, job: F) -> Result<T, Error>
where
F: FnOnce(crate::Client) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, Error>> + Send + 'static,
{
let retry = self.retry.clone();
self.submit(move |client| async move {
let client = match retry {
Some(retry) => client.with_retry(retry)?,
None => client,
};
Ok(job(client).await?)
})
.map_err(|failure| failure.error)
}
}

fn worker_error() -> CallFailure {
Expand Down Expand Up @@ -275,6 +330,7 @@ impl ClientBuilder {
setting!(user_id, impl Into<String>);
setting!(session_id, impl Into<String>);
setting!(run_id, impl Into<String>);
setting!(consumer, impl Into<String>);
setting!(timeout, Duration);
setting!(retry, RetryPolicy);
setting!(pacing, bool);
Expand Down Expand Up @@ -306,7 +362,7 @@ impl ClientBuilder {
return;
}
};
if ready.send(Ok(())).is_err() {
if ready.send(Ok(client.token_claims().cloned())).is_err() {
return;
}
while let Some(job) = receiver.recv().await {
Expand All @@ -318,12 +374,13 @@ impl ClientBuilder {
Error::Configuration(format!("cannot start blocking worker: {error}"))
})?;
match startup.recv() {
Ok(Ok(())) => Ok(Client {
Ok(Ok(claims)) => Ok(Client {
worker: Arc::new(Worker {
sender: Some(sender),
thread: Some(worker),
}),
retry: None,
claims: claims.map(Arc::new),
}),
result => {
drop(sender);
Expand All @@ -333,7 +390,7 @@ impl ClientBuilder {
Err(_) => Err(Error::Configuration(
"blocking client worker stopped during startup".into(),
)),
Ok(Ok(())) => unreachable!("success handled above"),
Ok(Ok(_)) => unreachable!("success handled above"),
}
}
}
Expand Down
96 changes: 94 additions & 2 deletions sdk/rust/src/capabilities.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
use std::collections::{BTreeMap, BTreeSet};
use std::{
collections::{BTreeMap, BTreeSet},
time::{Duration, Instant},
};

use crate::OpsCapabilitiesOutput;
use crate::{
token::{claim_allows, role_on},
wire_models::{NAMESPACE_HINT_EXCLUSIONS, OP_POLICIES},
OpCapability, OpsCapabilitiesOutput, TokenClaims,
};

pub(crate) fn supports_namespace_hint(op: &str) -> bool {
// Some ops take a namespace without authorizing the request on it.
NAMESPACE_HINT_EXCLUSIONS.binary_search(&op).is_err()
&& OP_POLICIES
.iter()
.any(|(name, _, _, keys, _)| *name == op && keys.contains(&"namespace"))
}

/// Operations and request fields an application needs from the server.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
Expand Down Expand Up @@ -32,6 +47,83 @@ impl ProbeRequest {
}
}

/// What the deployment serves and what this token may call.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Capabilities {
served: BTreeMap<String, OpCapability>,
pub build_commit: String,
pub schema_version: String,
/// The bearer token's payload; `None` when it is not a decodable JWT.
pub claims: Option<TokenClaims>,
fetched_at: Instant,
}

impl Capabilities {
pub(crate) fn new(output: OpsCapabilitiesOutput, claims: Option<TokenClaims>) -> Self {
let served = output
.ops
.into_iter()
.filter(|op| !op.name.is_empty())
.map(|mut op| {
op.required_role = op.required_role.to_lowercase();
(op.name.clone(), op)
})
.collect();
Self {
served,
build_commit: output.build_commit,
schema_version: output.schema_version,
claims,
fetched_at: Instant::now(),
}
}

/// The served operations by name, each with its lowercased required role.
pub fn ops(&self) -> &BTreeMap<String, OpCapability> {
&self.served
}

/// The deployment serves this op.
pub fn has(&self, op: &str) -> bool {
self.served.contains_key(op)
}

/// The op's minimum role, lowercased, when served and declared.
pub fn required_role(&self, op: &str) -> Option<&str> {
let role = self.served.get(op)?.required_role.trim();
(!role.is_empty()).then_some(role)
}

/// The token's role on `namespace`; `None` when unknown.
pub fn role(&self, namespace: Option<&str>) -> Option<&str> {
role_on(self.claims.as_ref(), namespace)
}

/// Compare the named namespace's token role with the operation's declared
/// role for operations with a bound namespace. `None` means the comparison
/// is unavailable. Live authorization can differ from this hint.
pub fn can_call(&self, op: &str, namespace: Option<&str>) -> Option<bool> {
if !supports_namespace_hint(op) {
return None;
}
claim_allows(self.claims.as_ref()?, namespace?, self.required_role(op)?)
}

/// Served ops whose declared role the token matches, sorted by name.
pub fn callable(&self, namespace: Option<&str>) -> Vec<String> {
self.served
.keys()
.filter(|op| self.can_call(op, namespace) == Some(true))
.cloned()
.collect()
}

pub(crate) fn age(&self) -> Duration {
self.fetched_at.elapsed()
}
}

/// A capability comparison. Missing capabilities do not produce an error.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
Expand Down
Loading
Loading