bws/command/
secret.rs

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
use bitwarden::{
    secrets_manager::{
        secrets::{
            SecretCreateRequest, SecretGetRequest, SecretIdentifiersByProjectRequest,
            SecretIdentifiersRequest, SecretPutRequest, SecretsDeleteRequest, SecretsGetRequest,
        },
        ClientSecretsExt,
    },
    Client,
};
use color_eyre::eyre::{bail, Result};
use uuid::Uuid;

use crate::{
    render::{serialize_response, OutputSettings},
    SecretCommand,
};

#[derive(Debug)]
pub(crate) struct SecretCreateCommandModel {
    pub(crate) key: String,
    pub(crate) value: String,
    pub(crate) note: Option<String>,
    pub(crate) project_id: Uuid,
}

#[derive(Debug)]
pub(crate) struct SecretEditCommandModel {
    pub(crate) id: Uuid,
    pub(crate) key: Option<String>,
    pub(crate) value: Option<String>,
    pub(crate) note: Option<String>,
    pub(crate) project_id: Option<Uuid>,
}

pub(crate) async fn process_command(
    command: SecretCommand,
    client: Client,
    organization_id: Uuid,
    output_settings: OutputSettings,
) -> Result<()> {
    match command {
        SecretCommand::List { project_id } => {
            list(client, organization_id, project_id, output_settings).await
        }
        SecretCommand::Get { secret_id } => get(client, secret_id, output_settings).await,
        SecretCommand::Create {
            key,
            value,
            note,
            project_id,
        } => {
            create(
                client,
                organization_id,
                SecretCreateCommandModel {
                    key,
                    value,
                    note,
                    project_id,
                },
                output_settings,
            )
            .await
        }
        SecretCommand::Edit {
            secret_id,
            key,
            value,
            note,
            project_id,
        } => {
            edit(
                client,
                organization_id,
                SecretEditCommandModel {
                    id: secret_id,
                    key,
                    value,
                    note,
                    project_id,
                },
                output_settings,
            )
            .await
        }
        SecretCommand::Delete { secret_ids } => delete(client, secret_ids).await,
    }
}

pub(crate) async fn list(
    client: Client,
    organization_id: Uuid,
    project_id: Option<Uuid>,
    output_settings: OutputSettings,
) -> Result<()> {
    let res = if let Some(project_id) = project_id {
        client
            .secrets()
            .list_by_project(&SecretIdentifiersByProjectRequest { project_id })
            .await?
    } else {
        client
            .secrets()
            .list(&SecretIdentifiersRequest { organization_id })
            .await?
    };

    let secret_ids = res.data.into_iter().map(|e| e.id).collect();
    let secrets = client
        .secrets()
        .get_by_ids(SecretsGetRequest { ids: secret_ids })
        .await?
        .data;
    serialize_response(secrets, output_settings);

    Ok(())
}

pub(crate) async fn get(
    client: Client,
    secret_id: Uuid,
    output_settings: OutputSettings,
) -> Result<()> {
    let secret = client
        .secrets()
        .get(&SecretGetRequest { id: secret_id })
        .await?;
    serialize_response(secret, output_settings);

    Ok(())
}

pub(crate) async fn create(
    client: Client,
    organization_id: Uuid,
    secret: SecretCreateCommandModel,
    output_settings: OutputSettings,
) -> Result<()> {
    let secret = client
        .secrets()
        .create(&SecretCreateRequest {
            organization_id,
            key: secret.key,
            value: secret.value,
            note: secret.note.unwrap_or_default(),
            project_ids: Some(vec![secret.project_id]),
        })
        .await?;
    serialize_response(secret, output_settings);

    Ok(())
}

pub(crate) async fn edit(
    client: Client,
    organization_id: Uuid,
    secret: SecretEditCommandModel,
    output_settings: OutputSettings,
) -> Result<()> {
    let old_secret = client
        .secrets()
        .get(&SecretGetRequest { id: secret.id })
        .await?;

    let new_secret = client
        .secrets()
        .update(&SecretPutRequest {
            id: secret.id,
            organization_id,
            key: secret.key.unwrap_or(old_secret.key),
            value: secret.value.unwrap_or(old_secret.value),
            note: secret.note.unwrap_or(old_secret.note),
            project_ids: secret
                .project_id
                .or(old_secret.project_id)
                .map(|id| vec![id]),
        })
        .await?;
    serialize_response(new_secret, output_settings);

    Ok(())
}

pub(crate) async fn delete(client: Client, secret_ids: Vec<Uuid>) -> Result<()> {
    let count = secret_ids.len();

    let result = client
        .secrets()
        .delete(SecretsDeleteRequest { ids: secret_ids })
        .await?;

    let secrets_failed: Vec<(Uuid, String)> = result
        .data
        .into_iter()
        .filter_map(|r| r.error.map(|e| (r.id, e)))
        .collect();
    let deleted_secrets = count - secrets_failed.len();

    match deleted_secrets {
        2.. => println!("{} secrets deleted successfully.", deleted_secrets),
        1 => println!("{} secret deleted successfully.", deleted_secrets),
        _ => (),
    }

    match secrets_failed.len() {
        2.. => eprintln!("{} secrets had errors:", secrets_failed.len()),
        1 => eprintln!("{} secret had an error:", secrets_failed.len()),
        _ => (),
    }

    for secret in &secrets_failed {
        eprintln!("{}: {}", secret.0, secret.1);
    }

    if !secrets_failed.is_empty() {
        bail!("Errors when attempting to delete secrets.");
    }

    Ok(())
}