difftreelog
feat postgres secret generator
10 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1045,7 +1045,10 @@
"ed25519-dalek",
"fleet-shared",
"hex",
+ "hmac",
+ "pbkdf2",
"rand 0.10.1",
+ "sha2",
"x25519-dalek",
]
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -31,6 +31,7 @@
futures = "0.3.31"
futures-util = { version = "0.3.31", features = ["sink"] }
hex = "0.4.3"
+hmac = "0.12"
hostname = "0.4.1"
human-repr = "1.1"
hyper = "1.8.1"
@@ -40,11 +41,12 @@
linked-hash-map = "0.5.6"
nix = { version = "0.31.2", features = ["fs", "user"] }
nom = "8.0.0"
+openssh = "0.11.5"
opentelemetry = "0.31.0"
+opentelemetry-appender-tracing = "0.31.1"
opentelemetry-otlp = { version = "0.31.0", features = ["grpc-tonic", "gzip-tonic", "http-json", "reqwest-rustls"] }
opentelemetry_sdk = "0.31.0"
-opentelemetry-appender-tracing = "0.31.1"
-openssh = "0.11.5"
+pbkdf2 = "0.12"
peg = "0.8.5"
pkg-config = "0.3.30"
rand = "0.10.0"
@@ -52,6 +54,7 @@
serde = { version = "1.0", features = ["derive"] }
serde-transcode = "1.1.1"
serde_json = "1.0"
+sha2 = "0.10"
shlex = "1.3"
tabled = "0.20.0"
tempfile = "3.20"
cmds/fleet/Cargo.tomldiffbeforeafterboth--- a/cmds/fleet/Cargo.toml
+++ b/cmds/fleet/Cargo.toml
@@ -44,12 +44,12 @@
indicatif = { workspace = true, optional = true }
nom.workspace = true
opentelemetry.workspace = true
+opentelemetry-appender-tracing.workspace = true
+opentelemetry-exporter-env.workspace = true
opentelemetry_sdk.workspace = true
thiserror.workspace = true
tracing-indicatif = { workspace = true, optional = true }
tracing-opentelemetry.workspace = true
-opentelemetry-exporter-env.workspace = true
-opentelemetry-appender-tracing.workspace = true
[features]
default = ["indicatif"]
cmds/generator-helper/Cargo.tomldiffbeforeafterboth--- a/cmds/generator-helper/Cargo.toml
+++ b/cmds/generator-helper/Cargo.toml
@@ -13,5 +13,8 @@
base64.workspace = true
ed25519-dalek.workspace = true
hex.workspace = true
+hmac.workspace = true
+pbkdf2.workspace = true
rand.workspace = true
+sha2.workspace = true
x25519-dalek.workspace = true
cmds/generator-helper/src/main.rsdiffbeforeafterboth--- a/cmds/generator-helper/src/main.rs
+++ b/cmds/generator-helper/src/main.rs
@@ -10,14 +10,30 @@
ssh::{ParseRecipientKeyError, Recipient as SshRecipient},
};
use anyhow::{Context, Result, anyhow, bail, ensure};
+use base64::{Engine as _, engine::general_purpose::STANDARD, write::EncoderWriter};
use clap::{Parser, ValueEnum};
use ed25519_dalek::SecretKey;
use fleet_shared::SecretData;
+use hmac::Mac as _;
use rand::{
Rng as _,
distr::{Alphanumeric, Distribution, SampleString, Uniform},
rng,
};
+use sha2::Digest as _;
+
+fn gen_password(rng: &mut impl rand::Rng, size: usize, no_symbols: bool) -> String {
+ if no_symbols {
+ Alphanumeric.sample_string(rng, size)
+ } else {
+ const GEN_ASCII_SYMBOLS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
+ let uniform = Uniform::new(0, GEN_ASCII_SYMBOLS.len()).expect("range is valid");
+ (0..size)
+ .map(|_| uniform.sample(rng))
+ .map(|i| GEN_ASCII_SYMBOLS[i] as char)
+ .collect::<String>()
+ }
+}
fn write_output_file(out: &str) -> Result<File> {
let file = OpenOptions::new()
@@ -105,8 +121,6 @@
match encoding {
OutputEncoding::Raw => coerce(w),
OutputEncoding::Base64 => {
- use base64::{engine::general_purpose::STANDARD, write::EncoderWriter};
-
let writer = EncoderWriter::new(w, &STANDARD);
coerce(writer)
}
@@ -177,6 +191,18 @@
#[arg(long, short = 'e', value_enum, default_value_t)]
encoding: OutputEncoding,
},
+ PostgresPassword {
+ #[arg(long, short = 's')]
+ secret: String,
+ #[arg(long, short = 'H')]
+ hash: String,
+ #[arg(long, default_value_t = 24)]
+ size: usize,
+ #[arg(long, default_value_t = 4096)]
+ iterations: u32,
+ #[arg(long, short = 'n')]
+ no_symbols: bool,
+ },
Bytes {
#[arg(long, short = 'o')]
output: String,
@@ -286,20 +312,62 @@
"misconfiguration? password is shorter than 6 chars"
);
let recipients = load_identities()?;
- let out = if no_symbols {
- Alphanumeric.sample_string(&mut rng, size)
- } else {
- // Alphabet of Alphanumberic + symbols
- const GEN_ASCII_SYMBOLS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
- let uniform =
- Uniform::new(0, GEN_ASCII_SYMBOLS.len()).expect("range is valid");
- (0..size)
- .map(|_| uniform.sample(&mut rng))
- .map(|i| GEN_ASCII_SYMBOLS[i] as char)
- .collect::<String>()
- };
+ let out = gen_password(&mut rng, size, no_symbols);
write_private(&recipients, &output, out.as_bytes(), encoding)?;
}
+ Generate::PostgresPassword {
+ secret,
+ hash,
+ size,
+ iterations,
+ no_symbols,
+ } => {
+ ensure!(
+ size >= 6,
+ "misconfiguration? password is shorter than 6 chars"
+ );
+ let recipients = load_identities()?;
+ let password = gen_password(&mut rng, size, no_symbols);
+
+ let mut salt = [0u8; 16];
+ rng.fill_bytes(&mut salt);
+ let salted = pbkdf2::pbkdf2_hmac_array::<sha2::Sha256, 32>(
+ password.as_bytes(),
+ &salt,
+ iterations,
+ );
+
+ type HmacSha256 = hmac::Hmac<sha2::Sha256>;
+ let mut mac = <HmacSha256 as hmac::Mac>::new_from_slice(&salted)
+ .expect("HMAC accepts any key length");
+ mac.update(b"Client Key");
+ let client_key = mac.finalize().into_bytes();
+
+ let mut hasher = sha2::Sha256::new();
+ hasher.update(client_key);
+ let stored_key = hasher.finalize();
+
+ let mut mac = <HmacSha256 as hmac::Mac>::new_from_slice(&salted)
+ .expect("HMAC accepts any key length");
+ mac.update(b"Server Key");
+ let server_key = mac.finalize().into_bytes();
+
+ let hash_str = format!(
+ "SCRAM-SHA-256${}:{}${}:{}",
+ iterations,
+ STANDARD.encode(salt),
+ STANDARD.encode(stored_key),
+ STANDARD.encode(server_key),
+ );
+
+ write_private(
+ &recipients,
+ &secret,
+ password.as_bytes(),
+ OutputEncoding::Raw,
+ )?;
+ write_public(&hash, hash_str.as_bytes(), OutputEncoding::Raw)?;
+ }
Generate::Bytes {
output,
count,
crates/nix-eval/src/lib.rsdiffbeforeafterboth--- a/crates/nix-eval/src/lib.rs
+++ b/crates/nix-eval/src/lib.rs
@@ -26,9 +26,8 @@
clear_err, copy_value, err_NIX_ERR_KEY, err_NIX_ERR_NIX_ERROR, err_NIX_ERR_OVERFLOW,
err_NIX_ERR_UNKNOWN, err_code, err_info_msg, err_msg, eval_state_build,
eval_state_builder_load, eval_state_builder_new, eval_state_builder_set_eval_setting,
- expr_eval_from_string, fetchers_settings,
- fetchers_settings_free, fetchers_settings_new, flake_lock, flake_lock_flags,
- flake_lock_flags_free, flake_lock_flags_new, flake_reference,
+ expr_eval_from_string, fetchers_settings, fetchers_settings_free, fetchers_settings_new,
+ flake_lock, flake_lock_flags, flake_lock_flags_free, flake_lock_flags_new, flake_reference,
flake_reference_and_fragment_from_string, flake_reference_parse_flags,
flake_reference_parse_flags_free, flake_reference_parse_flags_new,
flake_reference_parse_flags_set_base_directory, flake_settings, flake_settings_free,
@@ -323,7 +322,9 @@
thread_local! {
static THREAD_STATE: RefCell<ThreadState> = RefCell::new(ThreadState::new().expect("thread state init shouldn't fail"));
}
-pub(crate) fn with_default_context<T>(f: impl FnOnce(*mut c_context, *mut c_eval_state) -> T) -> Result<T> {
+pub(crate) fn with_default_context<T>(
+ f: impl FnOnce(*mut c_context, *mut c_eval_state) -> T,
+) -> Result<T> {
let global = &GLOBAL_STATE.state;
let (ctx, state) = THREAD_STATE.with_borrow_mut(|w| (w.ctx.0, global.0));
let mut ctx = NixContext(ctx);
@@ -439,7 +440,11 @@
}
}
-pub(crate) unsafe extern "C" fn copy_nix_str(start: *const c_char, n: c_uint, user_data: *mut c_void) {
+pub(crate) unsafe extern "C" fn copy_nix_str(
+ start: *const c_char,
+ n: c_uint,
+ user_data: *mut c_void,
+) {
let s = unsafe { slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).expect("c string has invalid utf-8");
unsafe { *user_data.cast::<String>() = s.to_owned() };
@@ -1128,8 +1133,8 @@
let test_result: String = nix_go_json!(builtins.uppercaseSuffix2("test")("suffix"));
assert_eq!(test_result, "TESTsuffix");
- let drv_path = nix_go!(attrs.packages["x86_64-linux"]["fleet-install-secrets"].drvPath)
- .to_string()?;
+ let drv_path =
+ nix_go!(attrs.packages["x86_64-linux"]["fleet-install-secrets"].drvPath).to_string()?;
let graph = drv::DrvGraph::resolve(&drv_path)?;
eprintln!(
"fleet-install-secrets dependency graph: {} nodes",
crates/nix-eval/src/logging.rsdiffbeforeafterboth--- a/crates/nix-eval/src/logging.rs
+++ b/crates/nix-eval/src/logging.rs
@@ -351,12 +351,15 @@
if let Some(entry) = drv_graph.get_mut(dep_path) {
entry.refcount += 1;
} else {
- drv_graph.insert(dep_path.clone(), DrvGraphEntry {
- name: dep_node.name.clone(),
- parent: Some(path.clone()),
- span: None,
- refcount: 1,
- });
+ drv_graph.insert(
+ dep_path.clone(),
+ DrvGraphEntry {
+ name: dep_node.name.clone(),
+ parent: Some(path.clone()),
+ span: None,
+ refcount: 1,
+ },
+ );
}
paths.push(dep_path.clone());
queue.push_back(dep_path.clone());
crates/opentelemetry-exporter-env/src/lib.rsdiffbeforeafterboth1use std::convert::Infallible;2use std::env::{self, VarError};3use std::ffi::OsString;4use std::num::ParseIntError;5use std::str::FromStr;6use std::time::Duration;78#[cfg(feature = "otlp")]9mod otlp;1011#[derive(thiserror::Error, Debug)]12pub enum Error {13 #[error("environment variable {env} contains invalid UTF-8: {value:?}")]14 InvalidUtf8 {15 env: &'static str,16 value: OsString,17 },18 #[error("environment variable {env}={value:?}: {error}")]19 EnvParse {20 env: &'static str,21 value: String,22 error: &'static str,23 },24 #[error("environment variable {env}={value:?}: {error}")]25 EnvParseInt {26 env: &'static str,27 value: String,28 error: ParseIntError,29 },30 #[cfg(feature = "otlp")]31 #[error("failed to build exporter: {0}")]32 Exporter(#[from] opentelemetry_otlp::ExporterBuildError),33}3435impl From<(&'static str, &'static str, String)> for Error {36 fn from((env, error, value): (&'static str, &'static str, String)) -> Self {37 Self::EnvParse { env, value, error }38 }39}40impl From<(&'static str, ParseIntError, String)> for Error {41 fn from((env, error, value): (&'static str, ParseIntError, String)) -> Self {42 Self::EnvParseInt { env, value, error }43 }44}45impl From<(&'static str, Infallible, String)> for Error {46 fn from(_v: (&'static str, Infallible, String)) -> Self {47 unreachable!()48 }49}5051fn load_env<T>(env: &'static str) -> Result<Option<T>, Error>52where53 T: FromStr,54 Error: From<(&'static str, <T as FromStr>::Err, String)>,55{56 match env::var(env) {57 Ok(v) => Ok(Some(T::from_str(&v).map_err(|err| (env, err, v))?)),58 Err(VarError::NotPresent) => Ok(None),59 Err(VarError::NotUnicode(value)) => Err(Error::InvalidUtf8 { env, value }),60 }61}6263macro_rules! impl_enum {64 (enum $id:ident {65 $(66 #[name = $value:literal]67 $var:ident,68 )*69 }) => {70 #[derive(Clone, Copy)]71 #[cfg_attr(feature = "clap", derive(clap::ValueEnum))]72 pub enum $id {73 $(74 #[cfg_attr(feature = "clap", value(name = $value))]75 $var,76 )*77 }78 impl FromStr for $id {79 type Err = &'static str;8081 fn from_str(s: &str) -> Result<Self, Self::Err> {82 Ok(match s {83 $(84 $value => Self::$var,85 )*86 _ => return Err("unsupported value")87 })88 }89 }90 };91}9293impl_enum! {94 enum ExporterKind {95 #[name = "otlp"]96 Otlp,97 #[name = "none"]98 None,99 }100}101102#[derive(Default)]103#[cfg_attr(feature = "clap", derive(clap::Parser))]104pub struct SignalExporterSettings {105 /// Traces exporter to be used.106 #[cfg_attr(feature = "clap", arg(long = "otel-traces-exporter", env = "OTEL_TRACES_EXPORTER", value_enum))]107 pub traces: Option<ExporterKind>,108 /// Metrics exporter to be used.109 #[cfg_attr(feature = "clap", arg(long = "otel-metrics-exporter", env = "OTEL_METRICS_EXPORTER", value_enum))]110 pub metrics: Option<ExporterKind>,111 /// Logs exporter to be used.112 #[cfg_attr(feature = "clap", arg(long = "otel-logs-exporter", env = "OTEL_LOGS_EXPORTER", value_enum))]113 pub logs: Option<ExporterKind>,114}115116impl SignalExporterSettings {117 pub fn from_env() -> Result<Self, Error> {118 Ok(Self {119 traces: load_env("OTEL_TRACES_EXPORTER")?,120 metrics: load_env("OTEL_METRICS_EXPORTER")?,121 logs: load_env("OTEL_LOGS_EXPORTER")?,122 })123 }124125 pub fn traces_enabled(&self) -> bool {126 !matches!(self.traces, Some(ExporterKind::None))127 }128 pub fn metrics_enabled(&self) -> bool {129 !matches!(self.metrics, Some(ExporterKind::None))130 }131 pub fn logs_enabled(&self) -> bool {132 !matches!(self.logs, Some(ExporterKind::None))133 }134}135136impl_enum! {137 enum Compression {138 #[name = "gzip"]139 Gzip,140 #[name = "zstd"]141 Zstd,142 }143}144#[cfg(feature = "otlp")]145impl From<Compression> for opentelemetry_otlp::Compression {146 fn from(value: Compression) -> Self {147 match value {148 Compression::Gzip => opentelemetry_otlp::Compression::Gzip,149 Compression::Zstd => opentelemetry_otlp::Compression::Zstd,150 }151 }152}153154impl_enum! {155 enum OtlpProtocol {156 #[name = "grpc"]157 Grpc,158 #[name = "http/protobuf"]159 HttpProtobuf,160 #[name = "http/json"]161 HttpJson,162 }163}164#[cfg(feature = "otlp")]165impl From<OtlpProtocol> for opentelemetry_otlp::Protocol {166 fn from(value: OtlpProtocol) -> Self {167 match value {168 OtlpProtocol::Grpc => opentelemetry_otlp::Protocol::Grpc,169 OtlpProtocol::HttpProtobuf => opentelemetry_otlp::Protocol::HttpBinary,170 OtlpProtocol::HttpJson => opentelemetry_otlp::Protocol::HttpJson,171 }172 }173}174175pub trait OtlpSignalSettings {176 fn compression(&self) -> Option<Compression>;177 fn endpoint(&self) -> Option<&str>;178 fn headers(&self) -> Option<&str>;179 fn protocol(&self) -> Option<OtlpProtocol>;180 fn timeout(&self) -> Option<u64>;181}182183macro_rules! impl_settings {184 (185 #[name($env_prefix:literal, $long_prefix:literal)]186 struct $id:ident {187 $(188 $(#[doc = $doc:literal])*189 #[name($env:literal, $long:literal)]190 $(#[arg($($tt:tt)*)])?191 $name:ident: $ty:ty,192 )*193 }) => {194 #[derive(Default)]195 #[cfg_attr(feature = "clap", derive(clap::Parser))]196 pub struct $id {197 $(198 $(#[doc = $doc])*199 #[cfg_attr(feature = "clap", arg(200 long = concat!("otel-exporter-otlp-", $long_prefix, $long),201 id = concat!("otel-exporter-otlp-", $long_prefix, $long),202 env = concat!("OTEL_EXPORTER_OTLP_", $env_prefix, $env)203 $(, $($tt)*)?)204 )]205 pub $name: Option<$ty>,206 )*207 }208 impl $id {209 pub fn from_env() -> Result<Self, Error> {210 Ok(Self {211 $(212 $name: load_env(concat!("OTEL_EXPORTER_OTLP_", $env_prefix, $env))?,213 )*214 })215 }216 }217 impl OtlpSignalSettings for $id {218 fn compression(&self) -> Option<Compression> { self.compression }219 fn endpoint(&self) -> Option<&str> { self.endpoint.as_deref() }220 fn headers(&self) -> Option<&str> { self.headers.as_deref() }221 fn protocol(&self) -> Option<OtlpProtocol> { self.protocol }222 fn timeout(&self) -> Option<u64> { self.timeout }223 }224 }225}226227impl_settings! {228 #[name("", "")]229 struct OtlpBaseSettings {230 /// Specifies the OTLP transport compression to be used for all telemetry data.231 #[name("COMPRESSION", "compression")]232 #[arg(value_enum)]233 compression: Compression,234 /// A base endpoint URL for any signal type, with an optionally-specified port number. Helpful for when you're sending more than one signal to the same endpoint and want one environment variable to control the endpoint.235 #[name("ENDPOINT", "endpoint")]236 endpoint: String,237 /// A list of headers to apply to all outgoing data (traces, metrics, and logs).238 #[name("HEADERS", "headers")]239 headers: String,240 /// Specifies the OTLP transport protocol to be used for all telemetry data.241 #[name("PROTOCOL", "protocol")]242 #[arg(value_enum)]243 protocol: OtlpProtocol,244 /// The timeout value for all outgoing data (traces, metrics, and logs) in milliseconds.245 #[name("TIMEOUT", "timeout")]246 timeout: u64,247 }248}249impl_settings! {250 #[name("LOGS_", "logs-")]251 struct OtlpLogsSettings {252 /// Specifies the OTLP transport compression to be used for log data.253 #[name("COMPRESSION", "compression")]254 #[arg(value_enum)]255 compression: Compression,256 /// Endpoint URL for log data only, with an optionally-specified port number. Typically ends with `v1/logs` when using OTLP/HTTP.257 #[name("ENDPOINT", "endpoint")]258 endpoint: String,259 /// A list of headers to apply to all outgoing logs.260 #[name("HEADERS", "headers")]261 headers: String,262 /// Specifies the OTLP transport protocol to be used for log data.263 #[name("PROTOCOL", "protocol")]264 #[arg(value_enum)]265 protocol: OtlpProtocol,266 /// The timeout value for all outgoing logs in milliseconds.267 #[name("TIMEOUT", "timeout")]268 timeout: u64,269 }270}271impl_settings! {272 #[name("METRICS_", "metrics-")]273 struct OtlpMetricsSettings {274 /// Specifies the OTLP transport compression to be used for metrics data.275 #[name("COMPRESSION", "compression")]276 #[arg(value_enum)]277 compression: Compression,278 /// Endpoint URL for metric data only, with an optionally-specified port number. Typically ends with `v1/metrics` when using OTLP/HTTP.279 #[name("ENDPOINT", "endpoint")]280 endpoint: String,281 /// A list of headers to apply to all outgoing metrics.282 #[name("HEADERS", "headers")]283 headers: String,284 /// Specifies the OTLP transport protocol to be used for metrics data.285 #[name("PROTOCOL", "protocol")]286 #[arg(value_enum)]287 protocol: OtlpProtocol,288 /// The timeout value for all outgoing metrics in milliseconds.289 #[name("TIMEOUT", "timeout")]290 timeout: u64,291 }292}293impl_settings! {294 #[name("TRACES_", "traces-")]295 struct OtlpTracesSettings {296 /// Specifies the OTLP transport compression to be used for trace data.297 #[name("COMPRESSION", "compression")]298 #[arg(value_enum)]299 compression: Compression,300 /// Endpoint URL for trace data only, with an optionally-specified port number. Typically ends with `v1/traces` when using OTLP/HTTP.301 #[name("ENDPOINT", "endpoint")]302 endpoint: String,303 /// A list of headers to apply to all outgoing traces.304 #[name("HEADERS", "headers")]305 headers: String,306 /// Specifies the OTLP transport protocol to be used for trace data.307 #[name("PROTOCOL", "protocol")]308 #[arg(value_enum)]309 protocol: OtlpProtocol,310 /// The timeout value for all outgoing traces in milliseconds.311 #[name("TIMEOUT", "timeout")]312 timeout: u64,313 }314}315316pub struct ResolvedOtlpSettings {317 pub compression: Option<Compression>,318 pub endpoint: String,319 pub headers: Option<String>,320 pub protocol: OtlpProtocol,321 pub timeout: Duration,322}323324impl ResolvedOtlpSettings {325 const DEFAULT_TIMEOUT_MS: u64 = 10000;326 const DEFAULT_GRPC_ENDPOINT: &str = "http://localhost:4317";327 const DEFAULT_HTTP_ENDPOINT: &str = "http://localhost:4318";328329 pub fn traces(330 base: &impl OtlpSignalSettings,331 signal: &impl OtlpSignalSettings,332 ) -> Result<Self, Error> {333 Self::resolve(base, signal, "/v1/traces")334 }335336 pub fn metrics(337 base: &impl OtlpSignalSettings,338 signal: &impl OtlpSignalSettings,339 ) -> Result<Self, Error> {340 Self::resolve(base, signal, "/v1/metrics")341 }342343 pub fn logs(344 base: &impl OtlpSignalSettings,345 signal: &impl OtlpSignalSettings,346 ) -> Result<Self, Error> {347 Self::resolve(base, signal, "/v1/logs")348 }349350 fn resolve(351 base: &impl OtlpSignalSettings,352 signal: &impl OtlpSignalSettings,353 signal_path: &str,354 ) -> Result<Self, Error> {355 let protocol = signal356 .protocol()357 .or_else(|| base.protocol())358 .unwrap_or(OtlpProtocol::HttpProtobuf);359360 let endpoint = if let Some(ep) = signal.endpoint() {361 ep.to_owned()362 } else if let Some(ep) = base.endpoint() {363 match protocol {364 OtlpProtocol::Grpc => ep.to_owned(),365 _ => format!("{ep}{signal_path}"),366 }367 } else {368 match protocol {369 OtlpProtocol::Grpc => Self::DEFAULT_GRPC_ENDPOINT.to_owned(),370 _ => format!("{}{signal_path}", Self::DEFAULT_HTTP_ENDPOINT),371 }372 };373374 Ok(Self {375 compression: signal.compression().or_else(|| base.compression()),376 endpoint,377 headers: signal378 .headers()379 .or_else(|| base.headers())380 .map(str::to_owned),381 protocol,382 timeout: Duration::from_millis(383 signal384 .timeout()385 .or_else(|| base.timeout())386 .unwrap_or(Self::DEFAULT_TIMEOUT_MS),387 ),388 })389 }390}crates/opentelemetry-exporter-env/src/otlp.rsdiffbeforeafterboth--- a/crates/opentelemetry-exporter-env/src/otlp.rs
+++ b/crates/opentelemetry-exporter-env/src/otlp.rs
@@ -55,15 +55,13 @@
}
builder.build()
}
- OtlpProtocol::HttpProtobuf | OtlpProtocol::HttpJson => {
- <$exporter>::builder()
- .with_http()
- .with_endpoint(&s.endpoint)
- .with_headers(to_hashmap(s.headers.as_deref()))
- .with_protocol(s.protocol.into())
- .with_timeout(s.timeout)
- .build()
- }
+ OtlpProtocol::HttpProtobuf | OtlpProtocol::HttpJson => <$exporter>::builder()
+ .with_http()
+ .with_endpoint(&s.endpoint)
+ .with_headers(to_hashmap(s.headers.as_deref()))
+ .with_protocol(s.protocol.into())
+ .with_timeout(s.timeout)
+ .build(),
}
}};
}
lib/default.nixdiffbeforeafterboth--- a/lib/default.nix
+++ b/lib/default.nix
@@ -89,6 +89,44 @@
);
/**
+ Generate a random password suitable for PostgreSQL role authentication.
+
+ Options:
+ size: generated password length in ascii characters (bytes).
+ iterations: PBKDF2 iteration count (PG default: 4096).
+ noSymbols: by default, character set includes various special characters ($ , ! + * : ~), and might
+ not be accepted in some contexts, this option switches charset to just [A-Za-z0-9].
+
+ Output:
+ secret: encrypted password.
+ hash: SCRAM-SHA-256 hash of the password to be used by postgres.
+ */
+ # It is not possible to extract it into a scram-sha-256 generic generator because there is no estabilished format
+ # for it, and mongodb for example encodes it differently.
+ mkPostgresPassword =
+ {
+ size ? 32,
+ iterations ? 4096,
+ noSymbols ? false,
+ }:
+ (
+ { mkSecretGenerator }:
+ mkSecretGenerator {
+ script = ''
+ mkdir $out
+ gh generate postgres-password \
+ -s $out/secret \
+ -H $out/hash \
+ --size ${toString size} \
+ --iterations ${toString iterations} \
+ ${optionalString noSymbols "--no-symbols"}
+ '';
+ parts.secret.encrypted = true;
+ parts.hash.encrypted = false;
+ }
+ );
+
+ /**
Generate a random ed25519 keypair
Options:
@@ -205,8 +243,7 @@
mkAskFile {
inherit part;
header = builtins.concatStringsSep "\n" (
- (map (l: "# ${l}") (lib.splitString "\n" header))
- ++ (map (v: "${v}=") variables)
+ (map (l: "# ${l}") (lib.splitString "\n" header)) ++ (map (v: "${v}=") variables)
);
};
@@ -306,6 +343,7 @@
inherit (secrets)
mkPassword
+ mkPostgresPassword
mkEd25519
mkX25519
mkRsa