Skip to main content

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 mz_postgres_util::{Sql, sql};
23use mz_sql_parser::ast::display::AstDisplay;
24
25use crate::{context::RegionContext, error::Error};
26
27/// Represents the args needed to create a secret
28pub struct CreateArgs<'a> {
29    /// Represents the database where the secret
30    /// is going to be created.
31    pub database: Option<&'a str>,
32    /// Represents the schema where the secret
33    /// is going to be created.
34    pub schema: Option<&'a str>,
35    /// Represents the secret name.
36    pub name: &'a str,
37    /// If force is set to true, the secret will be overwritten if it exists.
38    ///
39    /// If force is set to false, the command will fail if the secret exists.
40    pub force: bool,
41}
42
43/// Creates a secret in the profile environment.
44/// Behind the scenes this command uses the `psql` to run
45/// the SQL commands.
46pub async fn create(
47    cx: &RegionContext,
48    CreateArgs {
49        database,
50        schema,
51        name,
52        force,
53    }: CreateArgs<'_>,
54) -> Result<(), Error> {
55    let mut buffer = String::new();
56
57    // Ask the user to write the secret
58    print!("Secret: ");
59    let _ = std::io::stdout().flush();
60    io::stdin().read_line(&mut buffer)?;
61    buffer = buffer.trim().to_string();
62
63    // Retrieve information to open the psql shell sessions.
64    let loading_spinner = cx.output_formatter().loading_spinner("Creating secret...");
65
66    let claims = cx.admin_client().claims().await?;
67    let region_info = cx.get_region_info().await?;
68    let user = claims.user()?;
69
70    let mut client = cx.sql_client().shell(&region_info, user, None);
71
72    // Build the queries to create the secret.
73    let mut commands: Vec<Sql> = vec![];
74    // Lowercase the name to match SQL's behavior for unquoted identifiers,
75    // since the CLI accepts names without quoting.
76    let name = Sql::ident(&name.to_lowercase());
77
78    if let Some(database) = database {
79        client.args(vec!["-d", database]);
80    }
81
82    if let Some(schema) = schema {
83        commands.push(sql!("SET search_path TO {}", Sql::ident(schema)));
84    }
85
86    // The most common ways to write a secret are:
87    // 1. Decode function: decode('c2VjcmV0Cg==', 'base64')
88    // 2. ASCII: 13de2601-24b4-4d8f-9931-375c0b2b5cd4
89    // For case 1) we pass through the expression as-is (it's a SQL expression, not a literal).
90    // For case 2) we escape the value as a string literal.
91    let value = if buffer.starts_with("decode") {
92        // Validate that `buffer` parses as a single SQL expression.
93        let expr = mz_sql_parser::parser::parse_expr(&buffer)
94            .map_err(|e| Error::InvalidSecretExpression(e.to_string()))?;
95        Sql::raw_unchecked(expr.to_ast_string_stable())
96    } else {
97        Sql::literal(&buffer)
98    };
99
100    if force {
101        // Rather than checking if the SECRET exists, do an upsert.
102        // Unfortunately the `-c` command in psql runs inside a transaction
103        // and CREATE and ALTER SECRET cannot be run inside a transaction block.
104        // The alternative is passing two `-c` commands to psql.
105
106        // Otherwise if the SECRET exists `psql` will display a NOTICE message.
107        commands.push(sql!("SET client_min_messages TO WARNING;"));
108        commands.push(sql!(
109            "CREATE SECRET IF NOT EXISTS {} AS {};",
110            name.clone(),
111            value.clone()
112        ));
113        commands.push(sql!("ALTER SECRET {} AS {};", name.clone(), value.clone()));
114    } else {
115        commands.push(sql!("CREATE SECRET {} AS {};", name, value));
116    }
117
118    commands.iter().for_each(|c| {
119        client.args(vec!["-c", c.as_str()]);
120    });
121
122    let output = client
123        .arg("-q")
124        .output()
125        .map_err(|err| Error::CommandExecutionError(err.to_string()))?;
126
127    if !output.status.success() {
128        let error_message = String::from_utf8_lossy(&output.stderr).to_string();
129        return Err(Error::CommandFailed(error_message));
130    }
131
132    loading_spinner.finish_and_clear();
133    Ok(())
134}