Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "codspeed-runner"
version = "5.0.1"
version = "5.0.2-alpha.1"
edition = "2024"
repository = "https://github.com/CodSpeedHQ/codspeed"
publish = false
Expand Down
2 changes: 0 additions & 2 deletions src/run_environment/buildkite/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,6 @@ impl RunEnvironmentProvider for BuildkiteProvider {
repository: self.repository.clone(),
ref_: self.ref_.clone(),
repository_root_path: self.repository_root_path.clone(),
gh_data: None,
gl_data: None,
local_data: None,
sender: None,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ expression: run_environment_metadata
"repository": "adrien-python-test",
"event": "pull_request",
"sender": null,
"ghData": null,
"glData": null,
"localData": null,
"repositoryRootPath": "/buildkite/builds/7b10eca7600b-1/my-org/buildkite-test/"
}
105 changes: 105 additions & 0 deletions src/run_environment/circleci/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use console::style;
use log::*;
use simplelog::SharedLogger;
use std::{env, io::Write};

use crate::{
logger::{GroupEvent, get_announcement_event, get_group_event, get_json_event},
run_environment::logger::should_provider_logger_handle_record,
};

/// A logger that prints logs in the format expected by CircleCI
///
/// CircleCI has no collapsible section markers, so groups are printed as plain
/// headers.
pub struct CircleCILogger {
log_level: LevelFilter,
}

impl CircleCILogger {
pub fn new() -> Self {
// force activation of colors: CircleCI renders ANSI sequences in its UI, but
// the output is not a TTY so colors would be disabled by default.
console::set_colors_enabled(true);

let log_level = env::var("CODSPEED_LOG")
.ok()
.and_then(|log_level| log_level.parse::<log::LevelFilter>().ok())
.unwrap_or(log::LevelFilter::Info);
Self { log_level }
}
}

impl Log for CircleCILogger {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
}

fn log(&self, record: &Record) {
if !should_provider_logger_handle_record(record) {
return;
}

let level = record.level();
let message = record.args();

if let Some(group_event) = get_group_event(record) {
match group_event {
GroupEvent::Start(name) | GroupEvent::StartOpened(name) => {
println!("{}", style(name).cyan().bold());
}
GroupEvent::End => {}
}
return;
}

if get_json_event(record).is_some() {
return;
}

if let Some(announcement) = get_announcement_event(record) {
println!("{}", style(announcement).green());
return;
}

if level > self.log_level {
return;
}

match level {
Level::Error => {
println!("{}", style(message).red());
}
Level::Warn => {
println!("{}", style(message).yellow());
}
Level::Info => {
println!("{message}");
}
Level::Debug => {
println!("{}", style(message).cyan());
}
Level::Trace => {
println!("{}", style(message).magenta());
}
}
}
Comment on lines +46 to +86

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can't we do better for logging?


fn flush(&self) {
std::io::stdout().flush().unwrap();
}
}

impl SharedLogger for CircleCILogger {
fn level(&self) -> LevelFilter {
self.log_level
}

fn config(&self) -> Option<&simplelog::Config> {
None
}

fn as_log(self: Box<Self>) -> Box<dyn Log> {
Box::new(*self)
}
}
5 changes: 5 additions & 0 deletions src/run_environment/circleci/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod logger;
mod oidc;
mod provider;

pub use provider::CircleCIProvider;
47 changes: 47 additions & 0 deletions src/run_environment/circleci/oidc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use std::process::Command;

use crate::prelude::*;

/// The CLI CircleCI makes available inside jobs.
const CIRCLECI_CLI: &str = "circleci";

/// Mints an OIDC token for `audience`.
///
/// The token CircleCI puts in `CIRCLE_OIDC_TOKEN` and `CIRCLE_OIDC_TOKEN_V2` cannot
/// be used instead: its audience is the id of the CircleCI organization, while
/// CodSpeed requires its own. Requesting the audience is what makes a token minted
/// for another integration unusable against CodSpeed, and vice versa.
///
/// Errors carry what the CLI itself reported, as only the first error of a chain is
/// shown outside of debug logging: callers should add their advice to that message
/// rather than wrap it.
///
/// <https://circleci.com/docs/guides/permissions-authentication/oidc-tokens-with-custom-claims/>
pub fn mint_token(audience: &str) -> Result<String> {
let claims = serde_json::json!({ "aud": audience }).to_string();

let output = Command::new(CIRCLECI_CLI)
.args(["run", "oidc", "get", "--claims", &claims])
.output()
.map_err(|error| anyhow!("Failed to run the `circleci` CLI: {error}"))?;

if !output.status.success() {
bail!(
"`circleci run oidc get` failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}

// CircleCI does not mask tokens minted this way in the job output, so the token
// must not reach the logs, here or in the callers.
let token = String::from_utf8(output.stdout)
.map_err(|_| anyhow!("The OIDC token minted by CircleCI is not valid UTF-8"))?
.trim()
.to_string();

if token.is_empty() {
bail!("`circleci run oidc get` returned an empty token");
}

Ok(token)
}
Loading