security-client-rs 0.1.1

Async Kibana client for security operations and Fleet management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Agent policies, which group the package policies an agent runs.
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use super::{Fleet, FleetPage, Item};
use crate::{
    Error, Result, Scope,
    http::{Method, Raw},
    pagination::paginated,
    request::endpoint,
};

/// An agent policy returned by Fleet, grouping the integrations assigned to agents.
///
/// Use [`Self::edit`] to change a retrieved policy while retaining its inactivity
/// timeout. `Debug` output counts package policies instead of printing them,
/// since their variables can hold credentials.
#[derive(Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct AgentPolicy {
    pub id: String,
    pub name: String,
    /// Namespace used for the policy's data streams, independent of the Kibana space.
    pub namespace: String,
    /// Configuration delivery revision. Fleet does not use it to reject concurrent edits.
    pub revision: u64,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    /// Present when listed with agent counts.
    #[serde(default)]
    pub agents: Option<u64>,
    /// Populated when listed with full policies.
    #[serde(default)]
    pub package_policies: Vec<Value>,
    /// Unmodeled response fields. An edit resubmits only the supported writable fields.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

impl AgentPolicy {
    /// Changes to this policy, bound to its ID. Required name and namespace
    /// start from the retrieved values. The inactivity timeout is retained
    /// because Kibana resets it to two weeks when it is omitted from an update.
    /// Other settings are left unchanged unless their setter is called.
    ///
    /// Returns [`Error::InvalidRequest`] if `extra["inactivity_timeout"]` is
    /// missing or is not an unsigned integer. Fetch the policy again rather
    /// than guessing its timeout.
    ///
    /// Fleet agent-policy updates do not enforce optimistic concurrency;
    /// [`revision`](Self::revision) tracks configuration delivery to agents.
    ///
    /// Renaming retains the timeout and leaves other optional settings unset:
    ///
    /// ```
    /// use security_client_rs::fleet::AgentPolicy;
    /// use serde_json::{from_value, json, to_value};
    ///
    /// let policy: AgentPolicy = from_value(json!({
    ///     "id": "policy-a", "name": "Endpoints", "namespace": "default",
    ///     "revision": 3, "inactivity_timeout": 3600, "description": "Keep this"
    /// }))?;
    /// let body = to_value(policy.edit()?.name("SOC endpoints"))?;
    /// assert_eq!(body, json!({
    ///     "name": "SOC endpoints", "namespace": "default", "inactivity_timeout": 3600
    /// }));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// To apply an edit:
    ///
    /// ```no_run
    /// # async fn rename(client: &security_client_rs::Kibana) -> security_client_rs::Result<()> {
    /// let fleet = client.fleet();
    /// let policy = fleet.get_agent_policy("policy-id").send().await?.json().await?.item;
    /// let edit = policy.edit()?.name("SOC endpoints").clear_data_output_id();
    /// fleet.edit_agent_policy(&edit).send().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn edit(&self) -> Result<AgentPolicyEdit> {
        let timeout = self
            .extra
            .get("inactivity_timeout")
            .and_then(Value::as_u64)
            .ok_or_else(|| {
                Error::InvalidRequest(
                    "agent policy edit requires a retrieved inactivity_timeout".into(),
                )
            })?;
        Ok(AgentPolicyEdit {
            id: self.id.clone(),
            policy: NewAgentPolicy::new(&self.name, &self.namespace).inactivity_timeout(timeout),
        })
    }
}

impl fmt::Debug for AgentPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentPolicy")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("namespace", &self.namespace)
            .field("revision", &self.revision)
            .field("status", &self.status)
            .field("agents", &self.agents)
            .field("package_policies", &self.package_policies.len())
            .finish_non_exhaustive()
    }
}

/// An agent policy definition for [`Fleet::create_agent_policy`] and
/// [`Fleet::update_agent_policy`].
/// For changes to a retrieved policy, prefer [`AgentPolicy::edit`] to retain
/// its inactivity timeout instead of accepting the server's default.
/// Optional settings are omitted until their setter is called.
#[derive(Clone, Debug, Serialize)]
pub struct NewAgentPolicy {
    name: String,
    namespace: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    monitoring_enabled: Option<Vec<String>>,
    /// Omitted, `null` for Fleet's default output, or an output ID.
    #[allow(clippy::option_option)]
    #[serde(skip_serializing_if = "Option::is_none")]
    data_output_id: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    inactivity_timeout: Option<u64>,
}

impl NewAgentPolicy {
    pub fn new(name: impl Into<String>, namespace: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            namespace: namespace.into(),
            description: None,
            monitoring_enabled: None,
            data_output_id: None,
            inactivity_timeout: None,
        }
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Agent self-monitoring to collect: `logs`, `metrics` and `traces`. Empty disables it.
    pub fn monitoring_enabled<I: IntoIterator<Item = S>, S: Into<String>>(
        mut self,
        kinds: I,
    ) -> Self {
        self.monitoring_enabled = Some(kinds.into_iter().map(Into::into).collect());
        self
    }

    /// Selects a data output explicitly. Without this setter or
    /// [`clear_data_output_id`](Self::clear_data_output_id), the field is omitted.
    /// Kibana requires a Platinum license to set a per-policy output.
    pub fn data_output_id(mut self, id: impl Into<String>) -> Self {
        self.data_output_id = Some(Some(id.into()));
        self
    }

    /// Sends `data_output_id: null` to use Fleet's default output.
    /// On update, omission keeps the existing selection; null clears it.
    ///
    /// ```
    /// use security_client_rs::fleet::NewAgentPolicy;
    /// use serde_json::{json, to_value};
    ///
    /// let policy = NewAgentPolicy::new("SOC endpoints", "default");
    /// assert!(to_value(&policy)?.get("data_output_id").is_none());
    /// let selected = policy.data_output_id("output-id");
    /// assert_eq!(to_value(&selected)?["data_output_id"], json!("output-id"));
    /// let cleared = selected.clear_data_output_id();
    /// assert_eq!(to_value(&cleared)?["data_output_id"], json!(null));
    /// # Ok::<(), serde_json::Error>(())
    /// ```
    pub fn clear_data_output_id(mut self) -> Self {
        self.data_output_id = Some(None);
        self
    }

    /// Seconds without check-in before an agent is considered inactive.
    pub fn inactivity_timeout(mut self, seconds: u64) -> Self {
        self.inactivity_timeout = Some(seconds);
        self
    }
}

/// Changes to a retrieved agent policy, created by [`AgentPolicy::edit`] and
/// sent with [`Fleet::edit_agent_policy`].
///
/// The request includes name, namespace and the retained inactivity timeout,
/// plus explicitly changed settings. It omits response metadata, package
/// policies and unknown fields. Unset optional fields keep their server values.
/// Fleet merges submitted attributes and does not check the policy's revision
/// for concurrent updates.
#[derive(Clone, Debug, Serialize)]
pub struct AgentPolicyEdit {
    #[serde(skip)]
    id: String,
    #[serde(flatten)]
    policy: NewAgentPolicy,
}

impl AgentPolicyEdit {
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.policy.name = name.into();
        self
    }

    pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
        self.policy.namespace = namespace.into();
        self
    }

    /// Sets the description. An empty string clears its text.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.policy = self.policy.description(description);
        self
    }

    /// Agent self-monitoring to collect: `logs`, `metrics` and `traces`.
    /// Empty disables it; leaving this unset retains the existing selection.
    pub fn monitoring_enabled<I: IntoIterator<Item = S>, S: Into<String>>(
        mut self,
        kinds: I,
    ) -> Self {
        self.policy = self.policy.monitoring_enabled(kinds);
        self
    }

    /// Selects a data output explicitly. Leaving this unset retains the
    /// existing output selection. Kibana requires a Platinum license to set it.
    pub fn data_output_id(mut self, id: impl Into<String>) -> Self {
        self.policy = self.policy.data_output_id(id);
        self
    }

    /// Clears the output selection with JSON null, restoring Fleet's default.
    pub fn clear_data_output_id(mut self) -> Self {
        self.policy = self.policy.clear_data_output_id();
        self
    }

    /// Seconds without check-in before an agent is considered inactive.
    /// Leaving this unset retains the retrieved timeout.
    pub fn inactivity_timeout(mut self, seconds: u64) -> Self {
        self.policy = self.policy.inactivity_timeout(seconds);
        self
    }
}

impl<'a> Fleet<'a> {
    /// Requests full policies, which populate [`AgentPolicy::package_policies`].
    /// Agent counts are opt-in through [`FindAgentPolicies::with_agent_count`].
    pub fn find_agent_policies(&self) -> FindAgentPolicies<'a> {
        FindAgentPolicies(
            self.0
                .request(
                    Method::GET,
                    Scope::Space,
                    &["api", "fleet", "agent_policies"],
                )
                .param("full", true),
        )
    }

    pub fn get_agent_policy(&self, id: &str) -> GetAgentPolicy<'a> {
        GetAgentPolicy(self.0.request(
            Method::GET,
            Scope::Space,
            &["api", "fleet", "agent_policies", id],
        ))
    }

    /// Creates a policy from a [`NewAgentPolicy`] or equivalent JSON.
    pub fn create_agent_policy<B: Serialize + ?Sized>(&self, policy: &B) -> CreateAgentPolicy<'a> {
        CreateAgentPolicy(
            self.0
                .request(
                    Method::POST,
                    Scope::Space,
                    &["api", "fleet", "agent_policies"],
                )
                .json(policy),
        )
    }

    /// Updates submitted attributes and increments the policy's revision.
    /// Name and namespace are required. Omitting `inactivity_timeout` resets
    /// it to the server's default; prefer [`edit_agent_policy`](Self::edit_agent_policy)
    /// with a retrieved policy's edit to retain it.
    ///
    /// The body must be a JSON object. Its optional `id` must be a string
    /// matching the path argument; conflicts fail locally with
    /// [`Error::InvalidRequest`]. This generic body does not bind an edit's
    /// captured ID or project writable fields; use `edit_agent_policy` for that.
    pub fn update_agent_policy<B: Serialize + ?Sized>(
        &self,
        id: &str,
        policy: &B,
    ) -> UpdateAgentPolicy<'a> {
        UpdateAgentPolicy(
            self.0
                .request(
                    Method::PUT,
                    Scope::Space,
                    &["api", "fleet", "agent_policies", id],
                )
                .json(policy)
                .check_body_id(id, false),
        )
    }

    /// Applies changes bound to a retrieved policy's ID, retaining its timeout.
    /// Optional settings are changed only when their setter was called.
    pub fn edit_agent_policy(&self, edit: &AgentPolicyEdit) -> UpdateAgentPolicy<'a> {
        self.update_agent_policy(&edit.id, edit)
    }

    pub fn delete_agent_policy(&self, id: &str) -> DeleteAgentPolicy<'a> {
        DeleteAgentPolicy(
            self.0
                .request(
                    Method::POST,
                    Scope::Space,
                    &["api", "fleet", "agent_policies", "delete"],
                )
                .nonempty("agentPolicyId", id)
                .field("agentPolicyId", id),
        )
    }

    pub fn copy_agent_policy(&self, id: &str, name: &str) -> CopyAgentPolicy<'a> {
        CopyAgentPolicy(
            self.0
                .request(
                    Method::POST,
                    Scope::Space,
                    &["api", "fleet", "agent_policies", id, "copy"],
                )
                .field("name", name),
        )
    }

    /// The agent configuration as YAML.
    pub fn download_agent_policy(&self, id: &str) -> DownloadAgentPolicy<'a> {
        DownloadAgentPolicy(self.0.request(
            Method::GET,
            Scope::Space,
            &["api", "fleet", "agent_policies", id, "download"],
        ))
    }
}

endpoint! {
    /// `GET /api/fleet/agent_policies`
    FindAgentPolicies => FleetPage<AgentPolicy>
}

impl FindAgentPolicies<'_> {
    /// Populates package policies. Enabled by default.
    pub fn full(self, full: bool) -> Self {
        Self(self.0.param("full", full))
    }

    /// Populates [`AgentPolicy::agents`]. Kibana 8.19 rejects this parameter,
    /// including when it is false.
    pub fn with_agent_count(self, enabled: bool) -> Self {
        Self(self.0.param("withAgentCount", enabled))
    }
}

endpoint! {
    /// `GET /api/fleet/agent_policies/{agentPolicyId}`
    GetAgentPolicy => Item<AgentPolicy>
}

endpoint! {
    /// `POST /api/fleet/agent_policies`
    CreateAgentPolicy => Item<AgentPolicy>
}

impl CreateAgentPolicy<'_> {
    /// Also adds the System integration to the new policy.
    pub fn sys_monitoring(self, enabled: bool) -> Self {
        Self(self.0.param("sys_monitoring", enabled))
    }
}

endpoint! {
    /// `PUT /api/fleet/agent_policies/{agentPolicyId}`
    UpdateAgentPolicy => Item<AgentPolicy>
}

endpoint! {
    /// `POST /api/fleet/agent_policies/delete`
    DeleteAgentPolicy => Value
}

impl DeleteAgentPolicy<'_> {
    /// Bypasses server validation checks that would otherwise prevent deletion.
    pub fn force(self, force: bool) -> Self {
        Self(self.0.field("force", force))
    }
}

endpoint! {
    /// `POST /api/fleet/agent_policies/{agentPolicyId}/copy`
    CopyAgentPolicy => Item<AgentPolicy>
}

impl CopyAgentPolicy<'_> {
    pub fn description(self, description: &str) -> Self {
        Self(self.0.field("description", description))
    }
}

endpoint! {
    /// `GET /api/fleet/agent_policies/{agentPolicyId}/download`
    DownloadAgentPolicy => Raw
}

impl DownloadAgentPolicy<'_> {
    /// Produces a configuration for a standalone, non-Fleet agent.
    pub fn standalone(self, enabled: bool) -> Self {
        Self(self.0.param("standalone", enabled))
    }

    /// Produces a Kubernetes manifest.
    pub fn kubernetes(self, enabled: bool) -> Self {
        Self(self.0.param("kubernetes", enabled))
    }
}

page_setters!(FindAgentPolicies);
sort_setters!(FindAgentPolicies);
paginated!(FindAgentPolicies => FleetPage<AgentPolicy>);