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 });
87 }
88 Ok(result)
89}
90
91pub fn decode_policy_active_reply(
93 bytes: &[u8],
94) -> Result<Option<ActivePolicy>, CredentialResolverError> {
95 let result = policy_result(bytes)?;
96 let value: Value = serde_json::from_str(result.get()).map_err(|_| invalid_policy_reply())?;
97 if [
98 "version",
99 "policy_sha256",
100 "policy_text",
101 "manifest_version",
102 ]
103 .iter()
104 .all(|key| value.get(key).is_some_and(Value::is_null))
105 {
106 return Ok(None);
107 }
108 let policy: ActivePolicy = serde_json::from_value(value).map_err(|_| invalid_policy_reply())?;
109 if policy.version == 0
110 || policy.manifest_version == 0
111 || !valid_lower_hex(&policy.policy_sha256, 64)
112 || policy.policy_text.is_empty()
113 {
114 return Err(invalid_policy_reply());
115 }
116 Ok(Some(policy))
117}
118
119pub fn decode_policy_token_reply(bytes: &[u8]) -> Result<PolicyToken, CredentialResolverError> {
121 #[derive(Deserialize)]
122 struct WireToken<'a> {
123 token: &'a str,
124 expires_at_ms: i64,
125 repositories: Vec<String>,
126 permissions: BTreeMap<String, String>,
127 }
128 let reply: WireToken<'_> =
129 serde_json::from_str(policy_result(bytes)?.get()).map_err(|_| invalid_policy_reply())?;
130 if reply.token.is_empty() || reply.expires_at_ms < 0 {
131 return Err(invalid_policy_reply());
132 }
133 Ok(PolicyToken {
134 token: Secret::new(reply.token.to_owned()),
135 expires_at_ms: reply.expires_at_ms,
136 repositories: reply.repositories,
137 permissions: reply.permissions,
138 })
139}
140
141#[cfg(feature = "transport")]
142impl ClaustrumCredentialResolver {
143 pub async fn policy_active(&self) -> Result<Option<ActivePolicy>, CredentialResolverError> {
145 let reply = self.policy_request(POLICY_ACTIVE_OP, json!({})).await?;
146 decode_policy_active_reply(reply.expose())
147 }
148
149 pub async fn policy_token(
151 &self,
152 request: PolicyTokenRequest<'_>,
153 ) -> Result<PolicyToken, CredentialResolverError> {
154 let reply = self.policy_request(POLICY_TOKEN_OP, request).await?;
155 decode_policy_token_reply(reply.expose())
156 }
157
158 pub async fn policy_watch(&self) -> Result<PolicyWatch, CredentialResolverError> {
160 let target = self
161 .live_target
162 .as_ref()
163 .ok_or_else(CredentialResolverError::unavailable)?;
164 tokio::time::timeout(target.call_deadline, async {
165 target
166 .connector
167 .connect_policy_watch()
168 .await?
169 .into_policy_watch()
170 .await
171 })
172 .await
173 .unwrap_or_else(|_| Err(LiveCredentialGetTarget::deadline_error(POLICY_WATCH_OP)))
174 }
175
176 async fn policy_request(
177 &self,
178 method: &str,
179 params: impl serde::Serialize,
180 ) -> Result<Secret<Vec<u8>>, CredentialResolverError> {
181 let target = self
182 .live_target
183 .as_ref()
184 .ok_or_else(CredentialResolverError::unavailable)?;
185 let bytes = serde_json::to_vec(&json!({ "method": method, "params": params }))
186 .map_err(|_| invalid_policy_reply())?;
187 target.sensitive_request(Secret::new(bytes), method).await
188 }
189}