batata-consul-client 0.0.2

Rust client for HashiCorp Consul or batata
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::client::HttpClient;
use crate::error::Result;
use crate::types::{QueryMeta, QueryOptions, WriteMeta, WriteOptions};

/// ACL token type
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ACLTokenType {
    #[serde(rename = "client")]
    Client,
    #[serde(rename = "management")]
    Management,
}

/// ACL policy
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLPolicy {
    /// Policy ID
    #[serde(rename = "ID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Policy name
    pub name: String,
    /// Policy description
    #[serde(default)]
    #[serde(skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Policy rules (HCL or JSON)
    #[serde(default)]
    #[serde(skip_serializing_if = "String::is_empty")]
    pub rules: String,
    /// Datacenters this policy applies to
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub datacenters: Vec<String>,
    /// Hash of the policy
    #[serde(default)]
    pub hash: String,
    /// Create index
    #[serde(default)]
    pub create_index: u64,
    /// Modify index
    #[serde(default)]
    pub modify_index: u64,
}

impl ACLPolicy {
    pub fn new(name: &str) -> Self {
        Self {
            id: None,
            name: name.to_string(),
            description: String::new(),
            rules: String::new(),
            datacenters: Vec::new(),
            hash: String::new(),
            create_index: 0,
            modify_index: 0,
        }
    }

    pub fn with_description(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    pub fn with_rules(mut self, rules: &str) -> Self {
        self.rules = rules.to_string();
        self
    }

    pub fn with_datacenters(mut self, datacenters: Vec<String>) -> Self {
        self.datacenters = datacenters;
        self
    }
}

/// ACL token policy link
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLTokenPolicyLink {
    /// Policy ID
    #[serde(rename = "ID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Policy name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

impl ACLTokenPolicyLink {
    pub fn by_id(id: &str) -> Self {
        Self {
            id: Some(id.to_string()),
            name: None,
        }
    }

    pub fn by_name(name: &str) -> Self {
        Self {
            id: None,
            name: Some(name.to_string()),
        }
    }
}

/// ACL token role link
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLTokenRoleLink {
    /// Role ID
    #[serde(rename = "ID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Role name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// ACL token
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLToken {
    /// Token accessor ID (public ID)
    #[serde(rename = "AccessorID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accessor_id: Option<String>,
    /// Token secret ID (private, used for authentication)
    #[serde(rename = "SecretID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secret_id: Option<String>,
    /// Token description
    #[serde(default)]
    #[serde(skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Policies attached to token
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub policies: Vec<ACLTokenPolicyLink>,
    /// Roles attached to token
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<ACLTokenRoleLink>,
    /// Service identities
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub service_identities: Vec<ACLServiceIdentity>,
    /// Node identities
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub node_identities: Vec<ACLNodeIdentity>,
    /// Whether this is a local token
    #[serde(default)]
    pub local: bool,
    /// Token expiration time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration_time: Option<String>,
    /// Token expiration TTL
    #[serde(rename = "ExpirationTTL")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration_ttl: Option<String>,
    /// Hash of the token
    #[serde(default)]
    pub hash: String,
    /// Create index
    #[serde(default)]
    pub create_index: u64,
    /// Modify index
    #[serde(default)]
    pub modify_index: u64,
}

impl ACLToken {
    pub fn new() -> Self {
        Self {
            accessor_id: None,
            secret_id: None,
            description: String::new(),
            policies: Vec::new(),
            roles: Vec::new(),
            service_identities: Vec::new(),
            node_identities: Vec::new(),
            local: false,
            expiration_time: None,
            expiration_ttl: None,
            hash: String::new(),
            create_index: 0,
            modify_index: 0,
        }
    }

    pub fn with_description(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    pub fn with_policy(mut self, policy: ACLTokenPolicyLink) -> Self {
        self.policies.push(policy);
        self
    }

    pub fn with_role(mut self, role: ACLTokenRoleLink) -> Self {
        self.roles.push(role);
        self
    }

    pub fn with_service_identity(mut self, identity: ACLServiceIdentity) -> Self {
        self.service_identities.push(identity);
        self
    }

    pub fn local_only(mut self) -> Self {
        self.local = true;
        self
    }
}

impl Default for ACLToken {
    fn default() -> Self {
        Self::new()
    }
}

/// ACL service identity
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLServiceIdentity {
    /// Service name
    pub service_name: String,
    /// Datacenters
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub datacenters: Vec<String>,
}

impl ACLServiceIdentity {
    pub fn new(service_name: &str) -> Self {
        Self {
            service_name: service_name.to_string(),
            datacenters: Vec::new(),
        }
    }

    pub fn with_datacenters(mut self, datacenters: Vec<String>) -> Self {
        self.datacenters = datacenters;
        self
    }
}

/// ACL node identity
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLNodeIdentity {
    /// Node name
    pub node_name: String,
    /// Datacenter
    pub datacenter: String,
}

impl ACLNodeIdentity {
    pub fn new(node_name: &str, datacenter: &str) -> Self {
        Self {
            node_name: node_name.to_string(),
            datacenter: datacenter.to_string(),
        }
    }
}

/// ACL role
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLRole {
    /// Role ID
    #[serde(rename = "ID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Role name
    pub name: String,
    /// Role description
    #[serde(default)]
    #[serde(skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Policies attached to role
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub policies: Vec<ACLTokenPolicyLink>,
    /// Service identities
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub service_identities: Vec<ACLServiceIdentity>,
    /// Node identities
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub node_identities: Vec<ACLNodeIdentity>,
    /// Hash
    #[serde(default)]
    pub hash: String,
    /// Create index
    #[serde(default)]
    pub create_index: u64,
    /// Modify index
    #[serde(default)]
    pub modify_index: u64,
}

impl ACLRole {
    pub fn new(name: &str) -> Self {
        Self {
            id: None,
            name: name.to_string(),
            description: String::new(),
            policies: Vec::new(),
            service_identities: Vec::new(),
            node_identities: Vec::new(),
            hash: String::new(),
            create_index: 0,
            modify_index: 0,
        }
    }

    pub fn with_description(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    pub fn with_policy(mut self, policy: ACLTokenPolicyLink) -> Self {
        self.policies.push(policy);
        self
    }
}

/// ACL replication status
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ACLReplicationStatus {
    /// Whether replication is enabled
    pub enabled: bool,
    /// Whether this is the primary datacenter
    pub running: bool,
    /// Source datacenter
    pub source_datacenter: String,
    /// Replicated index
    pub replicated_index: u64,
    /// Replicated token index
    pub replicated_token_index: u64,
    /// Last success time
    pub last_success: String,
    /// Last error time
    pub last_error: String,
}

/// ACL API client
pub struct ACL {
    client: Arc<HttpClient>,
}

impl ACL {
    /// Create a new ACL client
    pub fn new(client: Arc<HttpClient>) -> Self {
        Self { client }
    }

    // Token operations

    /// Create a new token
    pub async fn token_create(&self, token: &ACLToken, opts: Option<&WriteOptions>) -> Result<(ACLToken, WriteMeta)> {
        let mut builder = self.client.put("/v1/acl/token").json(token);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Update an existing token
    pub async fn token_update(&self, token: &ACLToken, opts: Option<&WriteOptions>) -> Result<(ACLToken, WriteMeta)> {
        let accessor_id = token.accessor_id.as_ref().ok_or_else(|| {
            crate::error::ConsulError::InvalidConfig("accessor_id is required for update".to_string())
        })?;

        let path = format!("/v1/acl/token/{}", accessor_id);
        let mut builder = self.client.put(&path).json(token);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Clone an existing token
    pub async fn token_clone(&self, accessor_id: &str, description: Option<&str>, opts: Option<&WriteOptions>) -> Result<(ACLToken, WriteMeta)> {
        let path = format!("/v1/acl/token/{}/clone", accessor_id);

        let body = if let Some(desc) = description {
            serde_json::json!({"Description": desc})
        } else {
            serde_json::json!({})
        };

        let mut builder = self.client.put(&path).json(&body);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Delete a token
    pub async fn token_delete(&self, accessor_id: &str, opts: Option<&WriteOptions>) -> Result<(bool, WriteMeta)> {
        let path = format!("/v1/acl/token/{}", accessor_id);
        let mut builder = self.client.delete(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write_bool(builder).await
    }

    /// Read a token by accessor ID
    pub async fn token_read(&self, accessor_id: &str, opts: Option<&QueryOptions>) -> Result<(ACLToken, QueryMeta)> {
        let path = format!("/v1/acl/token/{}", accessor_id);
        let mut builder = self.client.get(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    /// Get the current token (self)
    pub async fn token_read_self(&self, opts: Option<&QueryOptions>) -> Result<(ACLToken, QueryMeta)> {
        let mut builder = self.client.get("/v1/acl/token/self");

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    /// List all tokens
    pub async fn token_list(&self, opts: Option<&QueryOptions>) -> Result<(Vec<ACLToken>, QueryMeta)> {
        let mut builder = self.client.get("/v1/acl/tokens");

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    // Policy operations

    /// Create a new policy
    pub async fn policy_create(&self, policy: &ACLPolicy, opts: Option<&WriteOptions>) -> Result<(ACLPolicy, WriteMeta)> {
        let mut builder = self.client.put("/v1/acl/policy").json(policy);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Update an existing policy
    pub async fn policy_update(&self, policy: &ACLPolicy, opts: Option<&WriteOptions>) -> Result<(ACLPolicy, WriteMeta)> {
        let id = policy.id.as_ref().ok_or_else(|| {
            crate::error::ConsulError::InvalidConfig("id is required for update".to_string())
        })?;

        let path = format!("/v1/acl/policy/{}", id);
        let mut builder = self.client.put(&path).json(policy);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Delete a policy
    pub async fn policy_delete(&self, id: &str, opts: Option<&WriteOptions>) -> Result<(bool, WriteMeta)> {
        let path = format!("/v1/acl/policy/{}", id);
        let mut builder = self.client.delete(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write_bool(builder).await
    }

    /// Read a policy by ID
    pub async fn policy_read(&self, id: &str, opts: Option<&QueryOptions>) -> Result<(ACLPolicy, QueryMeta)> {
        let path = format!("/v1/acl/policy/{}", id);
        let mut builder = self.client.get(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    /// Read a policy by name
    pub async fn policy_read_by_name(&self, name: &str, opts: Option<&QueryOptions>) -> Result<(ACLPolicy, QueryMeta)> {
        let path = format!("/v1/acl/policy/name/{}", name);
        let mut builder = self.client.get(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    /// List all policies
    pub async fn policy_list(&self, opts: Option<&QueryOptions>) -> Result<(Vec<ACLPolicy>, QueryMeta)> {
        let mut builder = self.client.get("/v1/acl/policies");

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    // Role operations

    /// Create a new role
    pub async fn role_create(&self, role: &ACLRole, opts: Option<&WriteOptions>) -> Result<(ACLRole, WriteMeta)> {
        let mut builder = self.client.put("/v1/acl/role").json(role);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Update an existing role
    pub async fn role_update(&self, role: &ACLRole, opts: Option<&WriteOptions>) -> Result<(ACLRole, WriteMeta)> {
        let id = role.id.as_ref().ok_or_else(|| {
            crate::error::ConsulError::InvalidConfig("id is required for update".to_string())
        })?;

        let path = format!("/v1/acl/role/{}", id);
        let mut builder = self.client.put(&path).json(role);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write(builder).await
    }

    /// Delete a role
    pub async fn role_delete(&self, id: &str, opts: Option<&WriteOptions>) -> Result<(bool, WriteMeta)> {
        let path = format!("/v1/acl/role/{}", id);
        let mut builder = self.client.delete(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_write_options(builder, opts);
        }

        self.client.write_bool(builder).await
    }

    /// Read a role by ID
    pub async fn role_read(&self, id: &str, opts: Option<&QueryOptions>) -> Result<(ACLRole, QueryMeta)> {
        let path = format!("/v1/acl/role/{}", id);
        let mut builder = self.client.get(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    /// Read a role by name
    pub async fn role_read_by_name(&self, name: &str, opts: Option<&QueryOptions>) -> Result<(ACLRole, QueryMeta)> {
        let path = format!("/v1/acl/role/name/{}", name);
        let mut builder = self.client.get(&path);

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    /// List all roles
    pub async fn role_list(&self, opts: Option<&QueryOptions>) -> Result<(Vec<ACLRole>, QueryMeta)> {
        let mut builder = self.client.get("/v1/acl/roles");

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }

    // Other ACL operations

    /// Bootstrap the ACL system
    pub async fn bootstrap(&self) -> Result<(ACLToken, WriteMeta)> {
        let builder = self.client.put("/v1/acl/bootstrap");
        self.client.write(builder).await
    }

    /// Get ACL replication status
    pub async fn replication(&self, opts: Option<&QueryOptions>) -> Result<(ACLReplicationStatus, QueryMeta)> {
        let mut builder = self.client.get("/v1/acl/replication");

        if let Some(opts) = opts {
            builder = self.client.apply_query_options(builder, opts);
        }

        self.client.query(builder).await
    }
}