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_sql_parser::ast::{
23 Ident,
24 display::{AstDisplay, escaped_string_literal},
25};
26
27use crate::{context::RegionContext, error::Error};
28
29/// Represents the args needed to create a secret
30pub struct CreateArgs<'a> {
31 /// Represents the database where the secret
32 /// is going to be created.
33 pub database: Option<&'a str>,
34 /// Represents the schema where the secret
35 /// is going to be created.
36 pub schema: Option<&'a str>,
37 /// Represents the secret name.
38 pub name: &'a str,
39 /// If force is set to true, the secret will be overwritten if it exists.
40 ///
41 /// If force is set to false, the command will fail if the secret exists.
42 pub force: bool,
43}
44
45/// Creates a secret in the profile environment.
46/// Behind the scenes this command uses the `psql` to run
47/// the SQL commands.
48pub async fn create(
49 cx: &RegionContext,
50 CreateArgs {
51 database,
52 schema,
53 name,
54 force,
55 }: CreateArgs<'_>,
56) -> Result<(), Error> {
57 let mut buffer = String::new();
58
59 // Ask the user to write the secret
60 print!("Secret: ");
61 let _ = std::io::stdout().flush();
62 io::stdin().read_line(&mut buffer)?;
63 buffer = buffer.trim().to_string();
64
65 // Retrieve information to open the psql shell sessions.
66 let loading_spinner = cx.output_formatter().loading_spinner("Creating secret...");
67
68 let claims = cx.admin_client().claims().await?;
69 let region_info = cx.get_region_info().await?;
70 let user = claims.user()?;
71
72 let mut client = cx.sql_client().shell(®ion_info, user, None);
73
74 // Build the queries to create the secret.
75 let mut commands: Vec<String> = vec![];
76
77 if let Some(database) = database {
78 client.args(vec!["-d", database]);
79 }
80
81 if let Some(schema) = schema {
82 let schema = Ident::new_unchecked(schema).to_ast_string_simple();
83 commands.push(format!("SET search_path TO {schema};"));
84 }
85
86 // The most common ways to write a secret are the following ways:
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 buffer = if buffer.starts_with("decode") {
92 buffer
93 } else {
94 escaped_string_literal(&buffer).to_string()
95 };
96 // Lowercase the name to match SQL's behavior for unquoted identifiers,
97 // since the CLI accepts names without quoting.
98 let name = Ident::new_unchecked(name.to_lowercase()).to_ast_string_simple();
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("SET client_min_messages TO WARNING;".to_string());
108 commands.push(format!(
109 "CREATE SECRET IF NOT EXISTS {} AS {};",
110 name, buffer
111 ));
112 commands.push(format!("ALTER SECRET {} AS {};", name, buffer));
113 } else {
114 commands.push(format!("CREATE SECRET {} AS {};", name, buffer));
115 }
116
117 commands.iter().for_each(|c| {
118 client.args(vec!["-c", c]);
119 });
120
121 let output = client
122 .arg("-q")
123 .output()
124 .map_err(|err| Error::CommandExecutionError(err.to_string()))?;
125
126 if !output.status.success() {
127 let error_message = String::from_utf8_lossy(&output.stderr).to_string();
128 return Err(Error::CommandFailed(error_message));
129 }
130
131 loading_spinner.finish_and_clear();
132 Ok(())
133}