mz/command/
secret.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Implementation of the `mz secret` command.
17//!
18//! Consult the user-facing documentation for details.
19
20use std::io::{self, Write};
21
22use crate::{context::RegionContext, error::Error};
23
24/// Represents the args needed to create a secret
25pub struct CreateArgs<'a> {
26    /// Represents the database where the secret
27    /// is going to be created.
28    pub database: Option<&'a str>,
29    /// Represents the schema where the secret
30    /// is going to be created.
31    pub schema: Option<&'a str>,
32    /// Represents the secret name.
33    pub name: &'a str,
34    /// If force is set to true, the secret will be overwritten if it exists.
35    ///
36    /// If force is set to false, the command will fail if the secret exists.
37    pub force: bool,
38}
39
40/// Creates a secret in the profile environment.
41/// Behind the scenes this command uses the `psql` to run
42/// the SQL commands.
43pub async fn create(
44    cx: &RegionContext,
45    CreateArgs {
46        database,
47        schema,
48        name,
49        force,
50    }: CreateArgs<'_>,
51) -> Result<(), Error> {
52    let mut buffer = String::new();
53
54    // Ask the user to write the secret
55    print!("Secret: ");
56    let _ = std::io::stdout().flush();
57    io::stdin().read_line(&mut buffer)?;
58    buffer = buffer.trim().to_string();
59
60    // Retrieve information to open the psql shell sessions.
61    let loading_spinner = cx.output_formatter().loading_spinner("Creating secret...");
62
63    let claims = cx.admin_client().claims().await?;
64    let region_info = cx.get_region_info().await?;
65    let user = claims.user()?;
66
67    let mut client = cx.sql_client().shell(&region_info, user, None);
68
69    // Build the queries to create the secret.
70    let mut commands: Vec<String> = vec![];
71
72    if let Some(database) = database {
73        client.args(vec!["-d", database]);
74    }
75
76    if let Some(schema) = schema {
77        commands.push(format!("SET search_path TO {}", schema));
78    }
79
80    // The most common ways to write a secret are the following ways:
81    // 1. Decode function: decode('c2VjcmV0Cg==', 'base64')
82    // 2. ASCII: 13de2601-24b4-4d8f-9931-375c0b2b5cd4
83    // For case 2) we want to scape the value for a better experience.
84    if !buffer.starts_with("decode") {
85        buffer = format!("'{}'", buffer);
86    }
87
88    if force {
89        // Rather than checking if the SECRET exists, do an upsert.
90        // Unfortunately the `-c` command in psql runs inside a transaction
91        // and CREATE and ALTER SECRET cannot be run inside a transaction block.
92        // The alternative is passing two `-c` commands to psql.
93
94        // Otherwise if the SECRET exists `psql` will display a NOTICE message.
95        commands.push("SET client_min_messages TO WARNING;".to_string());
96        commands.push(format!(
97            "CREATE SECRET IF NOT EXISTS {} AS {};",
98            name, buffer
99        ));
100        commands.push(format!("ALTER SECRET {} AS {};", name, buffer));
101    } else {
102        commands.push(format!("CREATE SECRET {} AS {};", name, buffer));
103    }
104
105    commands.iter().for_each(|c| {
106        client.args(vec!["-c", c]);
107    });
108
109    let output = client
110        .arg("-q")
111        .output()
112        .map_err(|err| Error::CommandExecutionError(err.to_string()))?;
113
114    if !output.status.success() {
115        let error_message = String::from_utf8_lossy(&output.stderr).to_string();
116        return Err(Error::CommandFailed(error_message));
117    }
118
119    loading_spinner.finish_and_clear();
120    Ok(())
121}