turnkey_tk 0.4.1

A CLI for machines to use Turnkey for git, ssh, and credential management
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
//! Resolves, decrypts, and delivers secret values. Pending exports persist a
//! recipient key so the same command can resume after approval.

use anyhow::{Context, Error, Result};
use rand_core::{OsRng, RngCore};
use serde::{Deserialize, Serialize};
use serde_json::{Value, from_slice, json, to_value, to_vec};
use std::fmt::Display;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use tokio::fs;
use tracing::warn;
use turnkey_client::generated::{
    ListSecretsRequest, ListSecretsResponse, SecretMetadata,
    external::options::v1::Pagination,
    immutable::{
        activity::v1::{ExportSecretParams, ExportSecretsIntent},
        models::v1::TransportEncryptionSuite,
    },
};
use turnkey_enclave_encrypt::{QuorumPublicKey, client::ExportClient};
use uuid::Uuid;
use zeroize::Zeroizing;

use super::input::{SecretName, SecretRef, UniqueKeyValues, quorum_for};
use super::{Listing, SecretOutput};
use crate::auth::{
    ResolvedAuth, SecureCreateError, build_turnkey_client, secure_create, state_dir,
};
use crate::errors::{ActivityError, ActivityErrorKind, InvalidInput, Malformed, MissingResource};
use crate::operations::{OperationOutput, observed, query, query_activity, submit_activity};

const COMMAND: &str = "secret.export";
const NEXT_STEP: &str = "After approval, run the same export command again.";

pub(super) async fn list(
    auth: ResolvedAuth,
    limit: u32,
    listing: Listing,
) -> Result<OperationOutput> {
    let limit = limit as usize;
    let (secrets, next_cursor) = match listing {
        Listing::Filtered { after, selector } => {
            let mut secrets = list_all(&auth, after, Some(limit + 1), |secret| {
                selector.matches(secret)
            })
            .await?;
            let next_cursor = (secrets.len() > limit).then(|| {
                secrets.pop();
                secrets.last().map(|secret| secret.secret_id.clone())
            });
            (secrets, next_cursor.flatten())
        }
        Listing::Page(cursor) => {
            let ResolvedAuth {
                org_id,
                api_base_url,
                stamper,
                ..
            } = auth;
            let client = build_turnkey_client(stamper, &api_base_url)?;
            let ListSecretsResponse { secrets } = client
                .list_secrets(ListSecretsRequest {
                    organization_id: org_id.to_string(),
                    pagination_options: Some(Pagination {
                        limit: limit.to_string(),
                        before: String::new(),
                        after: cursor.map(|id| id.to_string()).unwrap_or_default(),
                    }),
                })
                .await?;
            let next_cursor = (secrets.len() == limit)
                .then(|| secrets.last().map(|secret| secret.secret_id.clone()))
                .flatten();
            (secrets, next_cursor)
        }
    };
    Ok(OperationOutput::result(
        "secret.list",
        json!({"secrets": to_value(secrets)?, "nextCursor": next_cursor}),
    ))
}

/// Identifies the credential and endpoint that own a pending export.
#[derive(Clone)]
pub(super) struct Binding {
    organization_id: Uuid,
    api_base_url: String,
    api_public_key: String,
}

impl Binding {
    pub(super) fn of(auth: &ResolvedAuth) -> Self {
        Self {
            organization_id: auth.org_id,
            api_base_url: auth.api_base_url.as_str().trim_end_matches('/').to_owned(),
            api_public_key: hex::encode(auth.stamper.compressed_public_key()),
        }
    }

    pub(super) fn pending_dir(&self, state: &Path) -> PathBuf {
        state
            .join("secrets/pending")
            .join(self.organization_id.to_string())
            .join(&self.api_public_key)
    }
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct PendingExport {
    version: u32,
    organization_id: Uuid,
    api_base_url: String,
    api_public_key: String,
    secret_id: Uuid,
    activity_id: String,
    target_public_key: String,
    key_material: Zeroizing<String>,
}

impl PendingExport {
    fn path(dir: &Path, secret_id: Uuid) -> PathBuf {
        dir.join(format!("{secret_id}.json"))
    }

    async fn load(path: &Path, binding: &Binding) -> Result<Option<Self>> {
        let bytes = match fs::read(path).await {
            Ok(bytes) => Zeroizing::new(bytes),
            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
        };
        let state: Self = from_slice(&bytes).map_err(|error| {
            Malformed::new(
                format!(
                    "pending export state {} is malformed; delete it to start over",
                    path.display()
                ),
                error,
            )
        })?;
        if state.version != 1 {
            return Err(InvalidInput(format!(
                "pending export state {} has unsupported version {}",
                path.display(),
                state.version
            ))
            .into());
        }
        let mismatch: Option<(&str, &dyn Display, &dyn Display)> =
            if state.organization_id != binding.organization_id {
                Some((
                    "organization",
                    &state.organization_id,
                    &binding.organization_id,
                ))
            } else if state.api_base_url != binding.api_base_url {
                Some(("API base URL", &state.api_base_url, &binding.api_base_url))
            } else if state.api_public_key != binding.api_public_key {
                Some(("credential", &state.api_public_key, &binding.api_public_key))
            } else {
                None
            };
        if let Some((field, stored, current)) = mismatch {
            return Err(InvalidInput(format!(
                r#"pending export state {} belongs to a different {field} ({stored}, not {current}); resume it with the identity that started it"#,
                path.display()
            ))
            .into());
        }
        Ok(Some(state))
    }

    async fn create(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).await?;
        }
        let bytes = Zeroizing::new(to_vec(self)?);
        secure_create(path, &bytes).await.map_err(|error| match error {
            SecureCreateError::Exists => InvalidInput(
                "another export of this secret is already pending; run the command again to continue it".into(),
            )
            .into(),
            SecureCreateError::Io(error) => Error::new(error).context("write pending export state"),
        })
    }

    fn recipient(&self, path: &Path, quorum: &QuorumPublicKey) -> Result<ExportClient> {
        let ikm = Zeroizing::new(hex::decode(&*self.key_material).map_err(|error| {
            Malformed::new(
                format!(
                    "pending export state {} has invalid key material; delete it to start over",
                    path.display()
                ),
                error,
            )
        })?);
        if ikm.len() != 32 {
            return Err(InvalidInput(format!(
                "pending export state {} key material must be 32 bytes",
                path.display()
            ))
            .into());
        }
        let recipient = ExportClient::dangerous_from_bytes(&*ikm, quorum);
        if recipient.target_public_key()? != self.target_public_key {
            return Err(InvalidInput(format!(
                "pending export state {} key material does not match its target key",
                path.display()
            ))
            .into());
        }
        Ok(recipient)
    }
}

pub(super) async fn list_all(
    auth: &ResolvedAuth,
    after: Option<Uuid>,
    cap: Option<usize>,
    mut keep: impl FnMut(&SecretMetadata) -> bool,
) -> Result<Vec<SecretMetadata>> {
    let mut secrets = Vec::new();
    let mut request = ListSecretsRequest {
        organization_id: auth.org_id.to_string(),
        pagination_options: Some(Pagination {
            limit: "100".into(),
            before: String::new(),
            after: after.map(|id| id.to_string()).unwrap_or_default(),
        }),
    };
    loop {
        let ListSecretsResponse { secrets: page } =
            query("/public/v1/query/list_secrets", &request, auth).await?;
        let full = page.len() == 100;
        if full
            && let Some(pagination) = &mut request.pagination_options
            && let Some(last) = page.last()
        {
            pagination.after = last.secret_id.clone();
        }
        let room = cap.map_or(usize::MAX, |cap| cap - secrets.len());
        secrets.extend(page.into_iter().filter(&mut keep).take(room));
        if !full || cap.is_some_and(|cap| secrets.len() >= cap) {
            break;
        }
    }
    Ok(secrets)
}

pub(super) async fn resolve_name(auth: &ResolvedAuth, name: SecretName) -> Result<Uuid> {
    let matches = list_all(auth, None, None, |secret| {
        secret.name.as_deref() == Some(name.as_str())
    })
    .await?;
    match matches.as_slice() {
        [] => Err(MissingResource::new("secret", name).into()),
        [one] => Uuid::parse_str(&one.secret_id).context("secret id from the API is not a UUID"),
        many => Err(InvalidInput(format!(
            "{} secrets are named {name}; export by id instead: {}",
            many.len(),
            many.iter()
                .map(|secret| secret.secret_id.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))
        .into()),
    }
}

pub(super) async fn remove(path: &Path) -> Result<()> {
    match fs::remove_file(path).await {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error).with_context(|| format!("remove {}", path.display())),
    }
}

pub(super) async fn run(
    auth: ResolvedAuth,
    secret: SecretRef,
    out: Option<PathBuf>,
    context: UniqueKeyValues,
) -> Result<SecretOutput> {
    let quorum = quorum_for(auth.api_base_url.as_str())?;
    let state_dir = state_dir()?;
    let secret_id = match secret {
        SecretRef::Id(id) => id,
        SecretRef::Name(name) => resolve_name(&auth, name).await?,
    };
    let binding = Binding::of(&auth);
    let pending_dir = binding.pending_dir(&state_dir);
    match export_value(&pending_dir, &quorum, binding, &auth, secret_id, context).await? {
        Exported::Decrypted {
            record,
            value,
            consumed,
        } => {
            let delivered = deliver(record, value, out).await?;
            if let Some(path) = consumed {
                remove(&path).await?;
            }
            Ok(delivered)
        }
        Exported::Pending(record) => Ok(record.into()),
    }
}

pub(super) enum Exported {
    Pending(OperationOutput),
    Decrypted {
        record: OperationOutput,
        value: Zeroizing<String>,
        consumed: Option<PathBuf>,
    },
}

pub(super) async fn export_value(
    pending_dir: &Path,
    quorum: &QuorumPublicKey,
    binding: Binding,
    auth: &ResolvedAuth,
    secret_id: Uuid,
    context: UniqueKeyValues,
) -> Result<Exported> {
    let path = PendingExport::path(pending_dir, secret_id);

    if let Some(state) = PendingExport::load(&path, &binding).await? {
        let fetched = query_activity(auth, &state.activity_id).await?;
        let record = match observed(COMMAND, export_data(secret_id, fetched)) {
            Ok(record) => record,
            Err(error) => {
                if let Err(remove_error) = remove(&path).await {
                    warn!(?remove_error, "pending export state was left behind");
                }
                return Err(error);
            }
        };
        if record.is_pending() {
            return Ok(Exported::Pending(pending(record)));
        }
        let recipient = state.recipient(&path, quorum)?;
        let value = decrypt(recipient, &record, auth.org_id).with_context(|| {
            format!(
                "decrypt the completed export; delete {} to start a new export",
                path.display()
            )
        })?;
        return Ok(Exported::Decrypted {
            record,
            value,
            consumed: Some(path),
        });
    }

    let mut ikm = Zeroizing::new([0u8; 32]);
    OsRng.fill_bytes(&mut *ikm);
    let recipient = ExportClient::dangerous_from_bytes(*ikm, quorum);
    let target_public_key = recipient.target_public_key()?;
    let submitted = submit_activity(
        auth,
        COMMAND,
        "export_secrets",
        "ACTIVITY_TYPE_EXPORT_SECRETS",
        &ExportSecretsIntent {
            secrets: vec![ExportSecretParams {
                secret_id: secret_id.to_string(),
                target_public_key: target_public_key.clone(),
                encryption_suite: TransportEncryptionSuite::EnclaveEncryptV1,
                request_context: context.into(),
            }],
        },
    )
    .await?;
    let record = OperationOutput::result(COMMAND, export_data(secret_id, submitted.into_data()));
    if record.is_pending() {
        let activity_id = record.data()["activity"]["id"]
            .as_str()
            .map(str::to_owned)
            .ok_or_else(|| {
                ActivityError::new(
                    ActivityErrorKind::MalformedResponse,
                    "pending export has no activity id",
                )
            })?;
        let state = PendingExport {
            version: 1,
            organization_id: binding.organization_id,
            api_base_url: binding.api_base_url,
            api_public_key: binding.api_public_key,
            secret_id,
            target_public_key,
            key_material: Zeroizing::new(hex::encode(ikm.as_slice())),
            activity_id,
        };
        state.create(&path).await.with_context(|| {
            format!(
                "save the recovery key for export activity {}; that export cannot be finished, so reject it and run a new export",
                state.activity_id
            )
        })?;
        return Ok(Exported::Pending(pending(record)));
    }
    let value = decrypt(recipient, &record, auth.org_id)?;
    Ok(Exported::Decrypted {
        record,
        value,
        consumed: None,
    })
}

fn pending(record: OperationOutput) -> OperationOutput {
    let mut data = record.into_data();
    strip_result(&mut data);
    data["nextStep"] = NEXT_STEP.into();
    OperationOutput::result(COMMAND, data)
}

fn decrypt(
    mut recipient: ExportClient,
    record: &OperationOutput,
    org_id: Uuid,
) -> Result<Zeroizing<String>> {
    let bundle = record.data()["activity"]["result"]["exportSecretsResult"]["secretPayloads"]
        .as_array()
        .and_then(|payloads| match payloads.as_slice() {
            [Value::String(bundle)] => Some(bundle.as_str()),
            _ => None,
        })
        .ok_or_else(|| {
            ActivityError::new(
                ActivityErrorKind::MalformedResponse,
                "export result did not contain exactly one payload",
            )
        })?;
    let value = Zeroizing::new(recipient.decrypt_secret(bundle, org_id.to_string())?);
    if value.is_empty() {
        return Err(ActivityError::new(
            ActivityErrorKind::MalformedResponse,
            "exported secret is empty",
        )
        .into());
    }
    Ok(value)
}

/// Removes ciphertext from command output.
fn strip_result(data: &mut Value) {
    if let Some(activity) = data["activity"].as_object_mut() {
        activity.remove("result");
    }
}

/// Builds the export result while retaining ciphertext for decryption.
fn export_data(secret_id: Uuid, response: Value) -> Value {
    let activity = &response["activity"];
    json!({
        "secretId": secret_id,
        "activity": {
            "id": activity["id"],
            "status": activity["status"],
            "type": activity["type"],
            "result": activity["result"],
        },
    })
}

async fn deliver(
    record: OperationOutput,
    value: Zeroizing<String>,
    out: Option<PathBuf>,
) -> Result<SecretOutput> {
    let mut data = record.into_data();
    strip_result(&mut data);
    match out {
        Some(path) => {
            secure_create(&path, value.as_bytes())
                .await
                .map_err(|error| match error {
                    SecureCreateError::Exists => Error::new(InvalidInput(format!(
                        "refusing to overwrite {}",
                        path.display()
                    ))),
                    SecureCreateError::Io(error) => {
                        Error::new(error).context(format!("write {}", path.display()))
                    }
                })?;
            data["out"] = path.to_string_lossy().into();
            Ok(OperationOutput::result(COMMAND, data).into())
        }
        None => {
            data["value"] = value.as_str().into();
            Ok(SecretOutput {
                record: OperationOutput::result(COMMAND, data),
                plain: Some(value),
            })
        }
    }
}

#[cfg(test)]
mod tests;