cortexkit_claustrum_client/
policy.rs1use crate::*;
2use serde::Deserialize;
3use serde_json::value::RawValue;
4
5#[cfg(feature = "transport")]
6pub(super) const POLICY_ACTIVE_OP: &str = "policy.active";
7#[cfg(feature = "transport")]
8pub(super) const POLICY_WATCH_OP: &str = "policy.watch";
9#[cfg(feature = "transport")]
10const POLICY_TOKEN_OP: &str = "credential.policy_token";
11
12#[derive(Debug, PartialEq, Eq, Deserialize)]
14pub struct ActivePolicy {
15 pub version: u64,
16 pub policy_sha256: String,
17 pub policy_text: String,
18 pub manifest_version: u64,
19}
20
21#[derive(Debug, Clone, Copy, serde::Serialize)]
22pub struct PolicyTokenRequest<'a> {
23 pub identity: &'a str,
24 pub service: &'a str,
25 pub kind: &'a str,
26 pub resource: &'a str,
27 pub policy_version: u64,
28}
29
30#[derive(Debug)]
31pub struct PolicyToken {
32 pub token: Secret<String>,
33 pub expires_at_ms: i64,
34 pub repositories: Vec<String>,
35 pub permissions: BTreeMap<String, String>,
36}
37
38pub(super) fn invalid_policy_reply() -> CredentialResolverError {
39 CredentialResolverError::new(
40 CredentialErrorClass::InvalidResponse,
41 "invalid policy reply",
42 )
43}
44
45#[derive(Deserialize)]
46struct PolicyReply<'a> {
47 #[serde(borrow)]
48 result: &'a RawValue,
49}
50
51#[derive(Deserialize)]
52struct MaybeRefusal<'a> {
53 #[serde(borrow)]
54 error: Option<PolicyRefusal<'a>>,
55}
56
57#[derive(Deserialize)]
58struct PolicyRefusal<'a> {
59 code: &'a str,
60 class: &'a str,
61}
62
63pub(super) fn policy_result(bytes: &[u8]) -> Result<&RawValue, CredentialResolverError> {
64 let reply: PolicyReply<'_> =
65 serde_json::from_slice(bytes).map_err(|_| invalid_policy_reply())?;
66 let result = reply.result;
67 if !result.get().starts_with('{') {
68 return Err(invalid_policy_reply());
69 }
70 let refusal: MaybeRefusal<'_> =
71 serde_json::from_str(result.get()).map_err(|_| invalid_policy_reply())?;
72 if let Some(error) = refusal.error {
73 let class = match error.class {
74 "permanent" => CredentialErrorClass::Permanent,
75 "transient" => CredentialErrorClass::Transient,
76 "auth_required" => CredentialErrorClass::AuthRequired,
77 _ => return Err(invalid_policy_reply()),
78 };
79 return Err(CredentialResolverError {
82 class,
83 code: error.code.to_owned(),
84 safe_message: "vault refused the policy operation".to_owned(),
85 established_route_dead: false,
86 sdk_route_credit_exhausted: false,
87 });
88 }
89 Ok(result)
90}
91
92pub fn decode_policy_active_reply(
94 bytes: &[u8],
95) -> Result<Option<ActivePolicy>, CredentialResolverError> {
96 let result = policy_result(bytes)?;
97 let value: Value = serde_json::from_str(result.get()).map_err(|_| invalid_policy_reply())?;
98 if [
99 "version",
100 "policy_sha256",
101 "policy_text",
102 "manifest_version",
103 ]
104 .iter()
105 .all(|key| value.get(key).is_some_and(Value::is_null))
106 {
107 return Ok(None);
108 }
109 let policy: ActivePolicy = serde_json::from_value(value).map_err(|_| invalid_policy_reply())?;
110 if policy.version == 0
111 || policy.manifest_version == 0
112 || !valid_lower_hex(&policy.policy_sha256, 64)
113 || policy.policy_text.is_empty()
114 {
115 return Err(invalid_policy_reply());
116 }
117 Ok(Some(policy))
118}
119
120pub fn decode_policy_token_reply(bytes: &[u8]) -> Result<PolicyToken, CredentialResolverError> {
122 #[derive(Deserialize)]
123 struct WireToken<'a> {
124 token: &'a str,
125 expires_at_ms: i64,
126 repositories: Vec<String>,
127 permissions: BTreeMap<String, String>,
128 }
129 let reply: WireToken<'_> =
130 serde_json::from_str(policy_result(bytes)?.get()).map_err(|_| invalid_policy_reply())?;
131 if reply.token.is_empty() || reply.expires_at_ms < 0 {
132 return Err(invalid_policy_reply());
133 }
134 Ok(PolicyToken {
135 token: Secret::new(reply.token.to_owned()),
136 expires_at_ms: reply.expires_at_ms,
137 repositories: reply.repositories,
138 permissions: reply.permissions,
139 })
140}
141
142#[cfg(feature = "transport")]
143impl ClaustrumCredentialResolver {
144 pub async fn policy_active(&self) -> Result<Option<ActivePolicy>, CredentialResolverError> {
146 let reply = self.policy_request(POLICY_ACTIVE_OP, json!({})).await?;
147 decode_policy_active_reply(reply.expose())
148 }
149
150 pub async fn policy_token(
152 &self,
153 request: PolicyTokenRequest<'_>,
154 ) -> Result<PolicyToken, CredentialResolverError> {
155 let reply = self.policy_request(POLICY_TOKEN_OP, request).await?;
156 decode_policy_token_reply(reply.expose())
157 }
158
159 pub async fn policy_watch(&self) -> Result<PolicyWatch, CredentialResolverError> {
161 let target = self
162 .live_target
163 .as_ref()
164 .ok_or_else(CredentialResolverError::unavailable)?;
165 tokio::time::timeout(target.call_deadline, async {
166 target
167 .connector
168 .connect_policy_watch()
169 .await?
170 .into_policy_watch()
171 .await
172 })
173 .await
174 .unwrap_or_else(|_| Err(LiveCredentialGetTarget::deadline_error(POLICY_WATCH_OP)))
175 }
176
177 async fn policy_request(
178 &self,
179 method: &str,
180 params: impl serde::Serialize,
181 ) -> Result<Secret<Vec<u8>>, CredentialResolverError> {
182 let target = self
183 .live_target
184 .as_ref()
185 .ok_or_else(CredentialResolverError::unavailable)?;
186 let bytes = serde_json::to_vec(&json!({ "method": method, "params": params }))
187 .map_err(|_| invalid_policy_reply())?;
188 target.sensitive_request(Secret::new(bytes), method).await
189 }
190}