Skip to content

Spin up should check required variables #3213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions crates/common/src/env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//! Environment variable utilities

/// Defines the default environment variable prefix used by Spin.
pub const DEFAULT_ENV_PREFIX: &str = "SPIN_VARIABLE";

/// Creates an environment variable key based on the given prefix and key.
pub fn env_key(prefix: Option<String>, key: &str) -> String {
let prefix = prefix.unwrap_or_else(|| DEFAULT_ENV_PREFIX.to_string());
let upper_key = key.to_ascii_uppercase();
let key = format!("{prefix}_{upper_key}");
key
}
1 change: 1 addition & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

pub mod arg_parser;
pub mod data_dir;
pub mod env;
pub mod paths;
pub mod sha256;
pub mod sloth;
Expand Down
1 change: 1 addition & 0 deletions crates/factors-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = { workspace = true }

[dependencies]
spin-app = { path = "../app" }
spin-common = { path = "../common" }
spin-factors = { path = "../factors" }
spin-loader = { path = "../loader" }
spin-telemetry = { path = "../telemetry", features = ["testing"] }
Expand Down
3 changes: 3 additions & 0 deletions crates/factors-test/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use spin_app::locked::LockedApp;
use spin_common::env::env_key;
use spin_factors::{
anyhow::{self, Context},
wasmtime::{component::Linker, Config, Engine},
Expand Down Expand Up @@ -100,6 +101,8 @@ impl<T: RuntimeFactors> TestEnvironment<T> {
pub async fn build_locked_app(manifest: &toml::Table) -> anyhow::Result<LockedApp> {
let toml_str = toml::to_string(manifest).context("failed serializing manifest")?;
let dir = tempfile::tempdir().context("failed creating tempdir")?;
// `foo` variable is set to require. As we're not providing a default value, env is checked.
std::env::set_var(env_key(None, "foo"), "baz");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still say we should be able to transform a TOML manifest into a LockedApp without doing validation on variables.

let path = dir.path().join("spin.toml");
std::fs::write(&path, toml_str).context("failed writing manifest")?;
spin_loader::from_file(&path, FilesMountStrategy::Direct, None).await
Expand Down
1 change: 1 addition & 0 deletions crates/loader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ spin-locked-app = { path = "../locked-app" }
spin-manifest = { path = "../manifest" }
spin-outbound-networking-config = { path = "../outbound-networking-config" }
spin-serde = { path = "../serde" }
spin-variables = { path = "../variables" }
tempfile = { workspace = true }
terminal = { path = "../terminal" }
tokio = { workspace = true }
Expand Down
20 changes: 18 additions & 2 deletions crates/loader/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, ensure, Context, Result};
use futures::{future::try_join_all, StreamExt};
use reqwest::Url;
use spin_common::{paths::parent_dir, sloth, ui::quoted_path};
use spin_common::{env::env_key, paths::parent_dir, sloth, ui::quoted_path};
use spin_locked_app::{
locked::{
self, ContentPath, ContentRef, LockedApp, LockedComponent, LockedComponentDependency,
LockedComponentSource, LockedTrigger,
},
values::{ValuesMap, ValuesMapBuilder},
Variable,
};
use spin_manifest::schema::v2::{self, AppManifest, KebabId, WasiFilesMount};
use spin_outbound_networking_config::allowed_hosts::{
Expand Down Expand Up @@ -88,7 +89,7 @@ impl LocalLoader {

let variables = variables
.into_iter()
.map(|(name, v)| Ok((name.to_string(), locked_variable(v)?)))
.map(|(name, v)| Self::env_checker((name.to_string(), locked_variable(v)?)))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing this here means appears to mean we can't even build the LockedApp without having the variables available. How does this worth with e.g. spin registry push or spin cloud deploy?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a nit, but doing this in the loader produces an error message that implies we can't understand the manifest (usually meaning invalid TOML or incorrect schema): that's potentially misleading.

.collect::<Result<_>>()?;

let triggers = triggers
Expand Down Expand Up @@ -135,6 +136,21 @@ impl LocalLoader {
})
}

fn env_checker((key, val): (String, Variable)) -> anyhow::Result<(String, Variable)> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function name needs to be more descriptive. What is it checking?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not clear why this takes a tuple rather than two parameters?

if val.default.is_none() {
if std::env::var(env_key(None, key.as_ref())).is_err() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can't assume that variables will come from the host environment. They could come from Vault or Azure KeyVault - for example passwords or tokens would typically be stashed in vaults and it would be rude to demand users create dummy EVs for them. Variable sources are defined in the runtime config file - you can't validate them until you have the runtime config providers lined up.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you know that the user is using the default prefix?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The environment provider appears to support a dotenv_path setting to merge values from a file - not clear that this is respected here?

Err(anyhow::anyhow!(
"Variable data not provided for {}",
quoted_path(key)
))
} else {
Ok((key, val))
}
} else {
Ok((key, val))
}
}

// Load the given component into a LockedComponent, ready for execution.
async fn load_component(
&self,
Expand Down
1 change: 1 addition & 0 deletions crates/variables/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ azure_identity = { git = "https://github.com/azure/azure-sdk-for-rust", rev = "8
azure_security_keyvault = { git = "https://github.com/azure/azure-sdk-for-rust", rev = "8c4caa251c3903d5eae848b41bb1d02a4d65231c" }
dotenvy = "0.15"
serde = { workspace = true }
spin-common = { path = "../common" }
spin-expressions = { path = "../expressions" }
spin-factor-variables = { path = "../factor-variables" }
spin-factors = { path = "../factors" }
Expand Down
12 changes: 2 additions & 10 deletions crates/variables/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
};

use serde::Deserialize;
use spin_common::env::env_key;
use spin_expressions::{Key, Provider};
use spin_factors::anyhow::{self, Context as _};
use spin_world::async_trait;
Expand All @@ -25,8 +26,6 @@ pub struct EnvVariablesConfig {
pub dotenv_path: Option<PathBuf>,
}

const DEFAULT_ENV_PREFIX: &str = "SPIN_VARIABLE";

type EnvFetcherFn = Box<dyn Fn(&str) -> Result<String, VarError> + Send + Sync>;

/// A [`Provider`] that uses environment variables.
Expand Down Expand Up @@ -71,14 +70,7 @@ impl EnvVariablesProvider {

/// Gets the value of a variable from the environment.
fn get_sync(&self, key: &Key) -> anyhow::Result<Option<String>> {
let prefix = self
.prefix
.clone()
.unwrap_or_else(|| DEFAULT_ENV_PREFIX.to_string());

let upper_key = key.as_ref().to_ascii_uppercase();
let env_key = format!("{prefix}_{upper_key}");

let env_key = env_key(self.prefix.clone(), key.as_ref());
self.query_env(&env_key)
}

Expand Down
Loading