Repository navigation
Embed the named environment API key directly for telemetry #5488
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
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,171 +1,140 @@ | ||
| //! Build-time telemetry provisioning shared by pack and generate. Private minting | ||
| //! credentials remain in the build process; artifacts receive only public ingestion. | ||
| use anyhow::{Context, Result, bail}; | ||
| use btel_settings::artifact::{ | ||
| ArtifactTelemetry, BytecodeDigest, EmbeddedIngestion, IngestionDestination, PublicCredential, | ||
| }; | ||
| //! Build-time API-key embedding shared by pack and generate. | ||
| use std::ffi::OsString; | ||
|
|
||
| use anyhow::{Context, Result}; | ||
| use btel_settings::artifact::{ArtifactTelemetry, EmbeddedCredential, EmbeddedIngestion}; | ||
| use clap::Args; | ||
|
|
||
| #[derive(Args, Clone, Debug, Default)] | ||
| pub struct EmbedTelemetryArgs { | ||
| /// Mint and embed a public ingestion credential for this build. | ||
| #[arg(long, help_heading = "Telemetry options")] | ||
| pub embed_telemetry: bool, | ||
| /// Existing environment to bind the embedded credential to. | ||
| #[arg( | ||
| long, | ||
| value_name = "NAME", | ||
| requires = "embed_telemetry", | ||
| help_heading = "Telemetry options" | ||
| )] | ||
| pub telemetry_environment: Option<String>, | ||
| /// Embed the value of this environment variable as the telemetry API key. | ||
| #[arg(long, value_name = "ENV_VAR", value_parser = parse_envvar, help_heading = "Telemetry options")] | ||
| pub embed_telemetry: Option<String>, | ||
| } | ||
|
|
||
| pub struct Provisioning { | ||
| client: bcs_api::Client, | ||
| authorization: bcs_api::credentials::RequestAuthorization, | ||
| project: String, | ||
| environment: String, | ||
| context: bcs_api::diagnostics::Context, | ||
| fn parse_envvar(name: &str) -> Result<String, String> { | ||
| let mut bytes = name.bytes(); | ||
| if matches!(bytes.next(), Some(b'a'..=b'z' | b'A'..=b'Z' | b'_')) | ||
| && bytes.all(|byte| matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_')) | ||
| { | ||
| Ok(name.to_owned()) | ||
| } else { | ||
| Err( | ||
| "expected an environment-variable name, for example BAML_WRAPPER_BOUNDARY_API_KEY" | ||
| .into(), | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| impl EmbedTelemetryArgs { | ||
| pub fn prepare( | ||
| &self, | ||
| policy: &mut ArtifactTelemetry, | ||
| default_environment: Option<&str>, | ||
| producer: &str, | ||
| ) -> Result<Option<Provisioning>> { | ||
| if !self.embed_telemetry { | ||
| return Ok(None); | ||
| } | ||
| let environment = self.telemetry_environment.as_deref().or(default_environment) | ||
| .filter(|value| !value.is_empty()) | ||
| .with_context(|| format!("Embedding telemetry requires an existing environment. Pass `--telemetry-environment=<name>` or set `{producer}.telemetry_environment` in baml.toml."))?.to_owned(); | ||
| let project = baml_env::string_var("BOUNDARY_PROJECT")?.or_else(|| policy.project.clone()) | ||
| .filter(|value| !value.is_empty()) | ||
| .context("Embedding telemetry requires a project. Set `[boundary].project = \"org/project\"` in baml.toml or set BOUNDARY_PROJECT=org/project.")?; | ||
| if project.split('/').count() != 2 || project.split('/').any(str::is_empty) { | ||
| bail!( | ||
| "BOUNDARY_PROJECT or boundary.project must have the form org_handle/project_name." | ||
| ); | ||
| pub fn apply(&self, policy: &mut ArtifactTelemetry) -> Result<()> { | ||
| self.apply_with(policy, baml_env::os_var)?; | ||
| if self.embed_telemetry.is_some() { | ||
| // Keep the selected build endpoint as the artifact's runtime default. | ||
| let endpoint = bcs_api::Endpoint::with_default(policy.api_url.as_deref())?; | ||
| policy.api_url = Some(endpoint.as_str().to_owned()); | ||
| } | ||
| let endpoint = bcs_api::Endpoint::with_default(policy.api_url.as_deref())?; | ||
| let key = baml_env::string_var("BOUNDARY_API_KEY")?; | ||
| let source = if key.is_some() { | ||
| bcs_api::diagnostics::CredentialSource::ApiKey | ||
| } else { | ||
| bcs_api::diagnostics::CredentialSource::SavedLogin | ||
| }; | ||
| let context = bcs_api::diagnostics::Context { | ||
| endpoint: Some(endpoint.clone()), | ||
| source, | ||
| operation: bcs_api::diagnostics::Operation::MintBuildToken, | ||
| }; | ||
| let credential = match key { | ||
| Some(key) => { | ||
| if key == bcs_api::credentials::LOCAL_API_KEY | ||
| || key.starts_with(bcs_api::credentials::PUBLIC_PREFIX) | ||
| { | ||
| bail!( | ||
| "Embedding telemetry requires a Boundary API key with mint permission, or an administrator's `baml auth login` session. BOUNDARY_API_KEY=local and public ingestion credentials cannot mint tokens." | ||
| ); | ||
| } | ||
| bcs_api::Secret::new(key) | ||
| } | ||
| None => bcs_api::Store::new(&endpoint) | ||
| .and_then(|store| store.read()) | ||
| .and_then(|saved| { | ||
| saved | ||
| .map(|saved| saved.refresh_token) | ||
| .ok_or(bcs_api::Error::MissingCredentials) | ||
| }) | ||
| .map_err(|error| { | ||
| context.report(error, bcs_api::diagnostics::Outcome::ArtifactBuildFailed) | ||
| })?, | ||
| }; | ||
| // The chosen build endpoint and project are defaults for the shipped artifact. | ||
| policy.project = Some(project.clone()); | ||
| policy.api_url = Some(endpoint.as_str().to_owned()); | ||
| let authorization = bcs_api::credentials::RequestAuthorization { | ||
| authentication: bcs_api::credentials::Authentication::shared( | ||
| endpoint.as_str(), | ||
| credential, | ||
| ), | ||
| target: None, | ||
| }; | ||
| Ok(Some(Provisioning { | ||
| client: bcs_api::Client::new(endpoint)?, | ||
| authorization, | ||
| project, | ||
| environment, | ||
| context, | ||
| })) | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| impl Provisioning { | ||
| pub fn mint(&self, digest: BytecodeDigest) -> Result<EmbeddedIngestion> { | ||
| let wire_digest = bcs_api::builds::BytecodeDigest { | ||
| version: digest.version, | ||
| algorithm: digest.algorithm.clone(), | ||
| value: digest.value.clone(), | ||
| }; | ||
| let request = bcs_api::builds::MintBuildToken { | ||
| target: bcs_api::builds::BuildTarget::Handle { | ||
| project: &self.project, | ||
| environment: &self.environment, | ||
| }, | ||
| bytecode_digest: &wire_digest, | ||
| fn apply_with( | ||
| &self, | ||
| policy: &mut ArtifactTelemetry, | ||
| mut read: impl FnMut(&str) -> Option<OsString>, | ||
| ) -> Result<()> { | ||
| let Some(name) = &self.embed_telemetry else { | ||
| return Ok(()); | ||
| }; | ||
| let minted = self | ||
| .client | ||
| .mint_build_token(&self.authorization, uuid::Uuid::new_v4(), &request) | ||
| .map_err(|error| { | ||
| self.context | ||
| .report(error, bcs_api::diagnostics::Outcome::ArtifactBuildFailed) | ||
| let value = read(name) | ||
| .with_context(|| { | ||
| format!("Cannot embed telemetry: environment variable {name} is not set.") | ||
| })? | ||
| .into_string() | ||
| .map_err(|_| { | ||
| anyhow::anyhow!( | ||
| "Cannot embed telemetry: environment variable {name} is not valid Unicode." | ||
| ) | ||
| })?; | ||
| Ok(EmbeddedIngestion { | ||
| token: PublicCredential::new(minted.token.expose().to_owned()), | ||
| token_id: minted.token_id, | ||
| build_id: minted.build_id, | ||
| product_id: minted.product_id, | ||
| destination: IngestionDestination { | ||
| org_id: minted.destination.org_id, | ||
| project_id: minted.destination.project_id, | ||
| environment_id: minted.destination.environment_id, | ||
| }, | ||
| bytecode_digest: digest, | ||
| }) | ||
| anyhow::ensure!( | ||
| !value.trim().is_empty(), | ||
| "Cannot embed telemetry: environment variable {name} is empty." | ||
| ); | ||
| policy.embedded = Some(Box::new(EmbeddedIngestion { | ||
| api_key: EmbeddedCredential::new(value), | ||
| })); | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn environment_default_does_not_enable_minting_and_missing_environment_explains_both_inputs() { | ||
| assert!( | ||
| EmbedTelemetryArgs::default() | ||
| .prepare(&mut ArtifactTelemetry::default(), Some("staging"), "pack") | ||
| .unwrap() | ||
| .is_none() | ||
| ); | ||
| for producer in ["pack", "bridge"] { | ||
| let args = EmbedTelemetryArgs { | ||
| embed_telemetry: true, | ||
| telemetry_environment: None, | ||
| }; | ||
| fn omission_never_reads_the_environment() { | ||
| EmbedTelemetryArgs::default() | ||
| .apply_with(&mut ArtifactTelemetry::default(), |_| { | ||
| panic!("unexpected read") | ||
| }) | ||
| .unwrap(); | ||
| } | ||
|
|
||
| #[test] | ||
| fn embeds_only_the_named_value_verbatim_and_redacts_debug() { | ||
| let args = EmbedTelemetryArgs { | ||
| embed_telemetry: Some("BAML_WRAPPER_BOUNDARY_API_KEY".into()), | ||
| }; | ||
| let mut policy = ArtifactTelemetry::default(); | ||
| args.apply_with(&mut policy, |name| { | ||
| assert_eq!(name, "BAML_WRAPPER_BOUNDARY_API_KEY"); | ||
| Some(" bdry_secret_embedded ".into()) | ||
| }) | ||
| .unwrap(); | ||
| let key = &policy.embedded.unwrap().api_key; | ||
| assert_eq!(key.expose(), " bdry_secret_embedded "); | ||
| assert_eq!(format!("{key:?}"), "[REDACTED]"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn missing_empty_and_non_unicode_values_fail_without_exposing_the_value() { | ||
| let args = EmbedTelemetryArgs { | ||
| embed_telemetry: Some("KEY".into()), | ||
| }; | ||
| for (value, expected) in [ | ||
| (None, "not set"), | ||
| (Some("".into()), "empty"), | ||
| (Some(" ".into()), "empty"), | ||
| ] { | ||
| let error = args | ||
| .prepare(&mut ArtifactTelemetry::default(), None, producer) | ||
| .err() | ||
| .unwrap(); | ||
| .apply_with(&mut ArtifactTelemetry::default(), |_| value.clone()) | ||
| .unwrap_err(); | ||
| assert_eq!( | ||
| error.to_string(), | ||
| format!( | ||
| r#"Embedding telemetry requires an existing environment. Pass `--telemetry-environment=<name>` or set `{producer}.telemetry_environment` in baml.toml."# | ||
| ) | ||
| format!("Cannot embed telemetry: environment variable KEY is {expected}.") | ||
| ); | ||
| } | ||
| #[cfg(unix)] | ||
| { | ||
| use std::os::unix::ffi::OsStringExt; | ||
| let error = args | ||
| .apply_with(&mut ArtifactTelemetry::default(), |_| { | ||
| Some(OsString::from_vec(vec![0xff])) | ||
| }) | ||
| .unwrap_err(); | ||
| assert_eq!( | ||
| error.to_string(), | ||
| "Cannot embed telemetry: environment variable KEY is not valid Unicode." | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn requires_a_variable_name() { | ||
| for name in ["KEY", "_KEY_2", "BAML_WRAPPER_BOUNDARY_API_KEY"] { | ||
| assert!(parse_envvar(name).is_ok()); | ||
| } | ||
| for name in ["", "1KEY", "KEY=value", "not a name"] { | ||
| assert!(parse_envvar(name).is_err()); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: BoundaryML/baml
Length of output: 41997
Script executed:
Repository: BoundaryML/baml
Length of output: 42236
Script executed:
Repository: BoundaryML/baml
Length of output: 41595
Sensitive Data Exposure
CWE: CWE-798 — Use of Hard-coded Credentials
View Security blast radius
Do not embed the release API key in wrapper artifacts.
The workflow passes
BAML_WRAPPER_BOUNDARY_API_KEYto--embed-telemetry, and the embedding path stores it inEmbeddedIngestion. The runtime sends the default embedded value asAuthorization: Bearer .... This replaces the previous per-build public ingestion credential with the raw release key.Restore per-build public ingestion credential minting, or use a separately rotatable key restricted to telemetry ingestion and explicitly safe to distribute. Keep the current candidates out of public publishing until then.