| 1 | //! Brokered secrets: a secret a job uses only to call an API never enters |
| 2 | //! its sandbox. Its row names the hosts it is for (settings.rs); when a job |
| 3 | //! starts, `job_spec` gives the job a stand-in in its place, one per job and |
| 4 | //! secret, and keeps here what the stand-in stands for, sealed and bound to |
| 5 | //! it, until the job's time is up. The runner Worker sees every HTTP and |
| 6 | //! HTTPS request a job on g1t's machines makes (services/runner broker.ts), |
| 7 | //! asks `brokered_secrets` with the job's token for its stand-ins, and puts |
| 8 | //! the real value in place of a stand-in on requests to the secret's hosts |
| 9 | //! as they leave. Anywhere else the stand-in goes as it is, which is |
| 10 | //! useless to whoever receives it. |
| 11 | //! |
| 12 | //! A self-hosted runner's traffic never passes the Worker, so a job there |
| 13 | //! gets the stand-in too, and a line in its log saying why it will not |
| 14 | //! work: the real value is never sent to a machine g1t does not run. |
| 15 | |
| 16 | use g1t_contracts::actions::{BrokeredSecret, JobCallArgs, STAND_IN_PREFIX}; |
| 17 | use g1t_contracts::time::rfc3339; |
| 18 | use g1t_contracts::Outcome; |
| 19 | use g1t_kit::now_ms; |
| 20 | use g1t_secrets::random_hex; |
| 21 | use serde::Deserialize; |
| 22 | use serde_json::{Map, Value}; |
| 23 | use worker::Result; |
| 24 | use worker::wasm_bindgen::JsValue; |
| 25 | |
| 26 | use crate::plan::LOG_INSERT; |
| 27 | use crate::{Actions, Count, check}; |
| 28 | |
| 29 | /// The most hosts one brokered secret names. |
| 30 | pub(crate) const MAX_HOSTS: usize = 20; |
| 31 | /// The shortest value a brokered secret may have: a shorter one would be |
| 32 | /// found, and swapped, inside unrelated secrets. |
| 33 | pub(crate) const MIN_VALUE_CHARS: usize = 8; |
| 34 | |
| 35 | /// Keeps a job's stand-in: what it stands for, sealed and bound to it. |
| 36 | pub(crate) const STAND_IN_INSERT: &str = |
| 37 | "INSERT OR REPLACE INTO brokered_secrets (stand_in, job_id, name, value, hosts, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)"; |
| 38 | /// A job's stand-ins that still work at `?2`. |
| 39 | pub(crate) const STAND_INS_OF_JOB: &str = |
| 40 | "SELECT stand_in, name, value, hosts FROM brokered_secrets WHERE job_id = ?1 AND expires_at > ?2"; |
| 41 | /// Stand-ins whose jobs' time is up. |
| 42 | pub(crate) const STAND_INS_EXPIRED: &str = "DELETE FROM brokered_secrets WHERE expires_at <= ?1"; |
| 43 | |
| 44 | /// A brokered secret as one reader resolved it: its key, real value and |
| 45 | /// the hosts it is for. |
| 46 | #[derive(Clone, Debug, PartialEq)] |
| 47 | pub(crate) struct Broker { |
| 48 | pub name: String, |
| 49 | pub value: String, |
| 50 | pub hosts: Vec<String>, |
| 51 | } |
| 52 | |
| 53 | /// A stand-in made for one job. |
| 54 | #[derive(Clone, Debug, PartialEq)] |
| 55 | pub(crate) struct StandIn { |
| 56 | pub stand_in: String, |
| 57 | pub broker: Broker, |
| 58 | } |
| 59 | |
| 60 | /// A new stand-in: the prefix and 48 random hex characters. |
| 61 | pub(crate) fn stand_in() -> String { |
| 62 | format!("{STAND_IN_PREFIX}{}", random_hex(24)) |
| 63 | } |
| 64 | |
| 65 | /// Puts a stand-in in place of each brokered value wherever it appears in |
| 66 | /// `secrets`, as a whole value or inside one a called workflow built from |
| 67 | /// it (`${{ secrets.USER }}:${{ secrets.TOKEN }}`), and returns the |
| 68 | /// stand-ins made: one per brokered value found, whatever keys it is under. |
| 69 | /// Longer values go first, so one that holds another is replaced whole. |
| 70 | pub(crate) fn substitute(secrets: &mut Map<String, Value>, brokers: &[Broker], mut make: impl FnMut() -> String) -> Vec<StandIn> { |
| 71 | let mut ordered: Vec<&Broker> = brokers.iter().filter(|b| b.value.chars().count() >= MIN_VALUE_CHARS).collect(); |
| 72 | ordered.sort_by_key(|b| std::cmp::Reverse(b.value.len())); |
| 73 | let mut made: Vec<StandIn> = Vec::new(); |
| 74 | for broker in ordered { |
| 75 | if made.iter().any(|m| m.broker.value == broker.value) { |
| 76 | continue; |
| 77 | } |
| 78 | let mut stand_in: Option<String> = None; |
| 79 | for value in secrets.values_mut() { |
| 80 | let Value::String(text) = value else { continue }; |
| 81 | if text.contains(&broker.value) { |
| 82 | let with = stand_in.get_or_insert_with(&mut make); |
| 83 | *text = text.replace(&broker.value, with); |
| 84 | } |
| 85 | } |
| 86 | if let Some(stand_in) = stand_in { |
| 87 | made.push(StandIn { stand_in, broker: broker.clone() }); |
| 88 | } |
| 89 | } |
| 90 | made |
| 91 | } |
| 92 | |
| 93 | /// What a job on a self-hosted runner is told for each brokered secret it |
| 94 | /// was given. |
| 95 | pub(crate) fn self_hosted_note(name: &str) -> String { |
| 96 | format!( |
| 97 | "##[warning]{name} is a brokered secret: this job has a stand-in for it, which g1t fills in only on its own machines for now. On a self-hosted runner, requests that use it will not be signed in." |
| 98 | ) |
| 99 | } |
| 100 | |
| 101 | /// A line of a job's log, stamped as the runner stamps its own. |
| 102 | pub(crate) fn stamped(text: &str) -> String { |
| 103 | let at = rfc3339(now_ms()); |
| 104 | text.lines().map(|line| format!("{at} {line}\n")).collect() |
| 105 | } |
| 106 | |
| 107 | #[derive(Deserialize)] |
| 108 | struct StandInRow { |
| 109 | stand_in: String, |
| 110 | name: String, |
| 111 | value: String, |
| 112 | hosts: String, |
| 113 | } |
| 114 | |
| 115 | impl Actions { |
| 116 | /// Keeps a job's stand-ins until its time is up, and marks the job so |
| 117 | /// its log is masked for their values. Stand-ins whose time is up go. |
| 118 | pub(crate) async fn keep_stand_ins(&self, job_id: &str, timeout_minutes: u32, stand_ins: &[StandIn]) -> Result<()> { |
| 119 | let Some(sealer) = &self.sealer else { return Ok(()) }; |
| 120 | let now = now_ms(); |
| 121 | let expires = now + (u64::from(timeout_minutes) * 60 + 600) * 1000; |
| 122 | let mut statements = vec![self.db.prepare(STAND_INS_EXPIRED).bind(&[(now as f64).into()])?]; |
| 123 | for made in stand_ins { |
| 124 | statements.push(self.db.prepare(STAND_IN_INSERT).bind(&[ |
| 125 | made.stand_in.as_str().into(), |
| 126 | job_id.into(), |
| 127 | made.broker.name.as_str().into(), |
| 128 | sealer.seal(&made.broker.value, &made.stand_in).into(), |
| 129 | serde_json::to_string(&made.broker.hosts)?.into(), |
| 130 | (expires as f64).into(), |
| 131 | ])?); |
| 132 | } |
| 133 | statements.push(self.db.prepare("UPDATE jobs SET brokered = 1 WHERE id = ?").bind(&[job_id.into()])?); |
| 134 | self.db.batch(statements).await?; |
| 135 | Ok(()) |
| 136 | } |
| 137 | |
| 138 | /// A job's stand-ins that still work, opened. |
| 139 | pub(crate) async fn stand_ins_of(&self, job_id: &str) -> Result<Vec<BrokeredSecret>> { |
| 140 | let Some(sealer) = &self.sealer else { return Ok(Vec::new()) }; |
| 141 | let rows = self |
| 142 | .db |
| 143 | .prepare(STAND_INS_OF_JOB) |
| 144 | .bind(&[job_id.into(), (now_ms() as f64).into()])? |
| 145 | .all() |
| 146 | .await? |
| 147 | .results::<StandInRow>()?; |
| 148 | Ok(rows |
| 149 | .into_iter() |
| 150 | .filter_map(|row| { |
| 151 | Some(BrokeredSecret { |
| 152 | value: sealer.open(&row.value, &row.stand_in)?, |
| 153 | hosts: serde_json::from_str(&row.hosts).unwrap_or_default(), |
| 154 | name: row.name, |
| 155 | stand_in: row.stand_in, |
| 156 | }) |
| 157 | }) |
| 158 | .collect()) |
| 159 | } |
| 160 | |
| 161 | /// Whether a job in the repository could be given a brokered secret: |
| 162 | /// its project or its workspace has one. Asked as a job starts, so the |
| 163 | /// runner sends the job's HTTP through the Worker even when its network |
| 164 | /// is open; a job that turns out to get none just goes the long way. |
| 165 | pub(crate) async fn may_broker(&self, repo_id: &str, namespace: &str) -> Result<bool> { |
| 166 | let Some(project) = self.project_of(repo_id).await? else { return Ok(false) }; |
| 167 | let found = self |
| 168 | .db |
| 169 | .prepare("SELECT COUNT(*) AS n FROM settings WHERE kind = 'secret' AND brokered_hosts IS NOT NULL AND owner IN (?, ?)") |
| 170 | .bind(&[project.id.as_str().into(), namespace.to_lowercase().into()])? |
| 171 | .first::<Count>(None) |
| 172 | .await?; |
| 173 | Ok(found.is_some_and(|count| count.n > 0)) |
| 174 | } |
| 175 | |
| 176 | /// Adds g1t's own lines to a job's log, under `step` (0 for its setup). |
| 177 | pub(crate) async fn note_log(&self, job_id: &str, step: u32, text: &str) -> Result<()> { |
| 178 | self.db |
| 179 | .prepare(LOG_INSERT) |
| 180 | .bind(&[job_id.into(), step.into(), stamped(text).into(), JsValue::NULL])? |
| 181 | .run() |
| 182 | .await?; |
| 183 | Ok(()) |
| 184 | } |
| 185 | |
| 186 | /// `brokered_secrets`: a running job's stand-ins and what they stand |
| 187 | /// for, for the runner Worker to fill in on the job's requests. Asked |
| 188 | /// with the job's own token, which only the runner and the job hold; |
| 189 | /// the API never passes this method on, so the job cannot ask it. The |
| 190 | /// Worker holds the token the job started with, so that one still |
| 191 | /// answers here after the job's harness swapped it for another |
| 192 | /// (`job_spec` with `rotate`), and nowhere else. |
| 193 | pub async fn brokered_secrets(&self, a: JobCallArgs) -> Result<Outcome<Vec<BrokeredSecret>>> { |
| 194 | let job = check!(self.job_for_started_token(&a).await?); |
| 195 | Ok(Outcome::Ok(self.stand_ins_of(&job.id).await?)) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | #[cfg(test)] |
| 200 | mod tests { |
| 201 | use rusqlite::{Connection, params}; |
| 202 | use serde_json::{Map, Value, json}; |
| 203 | |
| 204 | use super::{Broker, STAND_IN_INSERT, STAND_INS_EXPIRED, STAND_INS_OF_JOB, self_hosted_note, stand_in, substitute}; |
| 205 | |
| 206 | fn broker(name: &str, value: &str, hosts: &[&str]) -> Broker { |
| 207 | Broker { name: name.into(), value: value.into(), hosts: hosts.iter().map(|h| (*h).to_owned()).collect() } |
| 208 | } |
| 209 | |
| 210 | fn counter() -> impl FnMut() -> String { |
| 211 | let mut n = 0; |
| 212 | move || { |
| 213 | n += 1; |
| 214 | format!("g1tsec_{n}") |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[test] |
| 219 | fn stand_ins_are_long_random_tokens() { |
| 220 | let one = stand_in(); |
| 221 | assert!(one.starts_with("g1tsec_")); |
| 222 | assert_eq!(one.len(), "g1tsec_".len() + 48); |
| 223 | assert!(one["g1tsec_".len()..].chars().all(|c| c.is_ascii_hexdigit())); |
| 224 | assert_ne!(one, stand_in()); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn a_brokered_value_never_reaches_the_job() { |
| 229 | let mut secrets: Map<String, Value> = json!({ |
| 230 | "NPM_TOKEN": "npm_realvalue123", |
| 231 | "ALSO_NPM": "npm_realvalue123", |
| 232 | "BASIC": "me:npm_realvalue123", |
| 233 | "PLAIN": "not-brokered-value", |
| 234 | }) |
| 235 | .as_object() |
| 236 | .cloned() |
| 237 | .unwrap(); |
| 238 | let made = substitute(&mut secrets, &[broker("NPM_TOKEN", "npm_realvalue123", &["registry.npmjs.org"])], counter()); |
| 239 | assert_eq!(made.len(), 1); |
| 240 | assert_eq!(made[0].stand_in, "g1tsec_1"); |
| 241 | assert_eq!(made[0].broker.hosts, ["registry.npmjs.org"]); |
| 242 | assert_eq!(secrets["NPM_TOKEN"], "g1tsec_1"); |
| 243 | assert_eq!(secrets["ALSO_NPM"], "g1tsec_1"); |
| 244 | assert_eq!(secrets["BASIC"], "me:g1tsec_1"); |
| 245 | assert_eq!(secrets["PLAIN"], "not-brokered-value"); |
| 246 | assert!(!serde_json::to_string(&secrets).unwrap().contains("npm_realvalue123")); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn each_secret_gets_its_own_stand_in_and_longer_values_go_first() { |
| 251 | let mut secrets: Map<String, Value> = |
| 252 | json!({ "SHORT": "abcdefgh", "LONG": "abcdefgh-and-more" }).as_object().cloned().unwrap(); |
| 253 | let made = substitute( |
| 254 | &mut secrets, |
| 255 | &[broker("SHORT", "abcdefgh", &["a.example.com"]), broker("LONG", "abcdefgh-and-more", &["b.example.com"])], |
| 256 | counter(), |
| 257 | ); |
| 258 | assert_eq!(made.len(), 2); |
| 259 | assert_eq!(made[0].broker.name, "LONG"); |
| 260 | assert_eq!(secrets["LONG"], "g1tsec_1"); |
| 261 | assert_eq!(secrets["SHORT"], "g1tsec_2"); |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn values_too_short_or_not_given_make_no_stand_in() { |
| 266 | let mut secrets: Map<String, Value> = json!({ "PIN": "1234" }).as_object().cloned().unwrap(); |
| 267 | assert!(substitute(&mut secrets, &[broker("PIN", "1234", &["x.example.com"])], counter()).is_empty()); |
| 268 | assert!(substitute(&mut secrets, &[broker("GONE", "absent-value", &["x.example.com"])], counter()).is_empty()); |
| 269 | assert_eq!(secrets["PIN"], "1234"); |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn the_self_hosted_note_is_a_warning_naming_the_secret() { |
| 274 | let note = self_hosted_note("NPM_TOKEN"); |
| 275 | assert!(note.starts_with("##[warning]NPM_TOKEN")); |
| 276 | assert!(note.contains("only on its own machines")); |
| 277 | } |
| 278 | |
| 279 | fn database() -> Connection { |
| 280 | let db = Connection::open_in_memory().unwrap(); |
| 281 | for name in ["0001_init.sql", "0019_brokered_secrets.sql"] { |
| 282 | let path = format!("{}/migrations/{name}", env!("CARGO_MANIFEST_DIR")); |
| 283 | db.execute_batch(&std::fs::read_to_string(path).unwrap()).unwrap(); |
| 284 | } |
| 285 | db |
| 286 | } |
| 287 | |
| 288 | #[test] |
| 289 | fn a_job_finds_only_its_own_stand_ins_while_they_work() { |
| 290 | let db = database(); |
| 291 | let keep = |stand_in: &str, job: &str, expires: i64| { |
| 292 | db.execute(STAND_IN_INSERT, params![stand_in, job, "NPM_TOKEN", "sealed", "[\"registry.npmjs.org\"]", expires]).unwrap() |
| 293 | }; |
| 294 | keep("g1tsec_a", "job_1", 2_000); |
| 295 | keep("g1tsec_b", "job_2", 2_000); |
| 296 | keep("g1tsec_c", "job_1", 500); |
| 297 | let of = |job: &str, now: i64| -> Vec<String> { |
| 298 | let mut rows = db.prepare(STAND_INS_OF_JOB).unwrap(); |
| 299 | rows.query_map(params![job, now], |row| row.get::<_, String>(0)).unwrap().map(Result::unwrap).collect() |
| 300 | }; |
| 301 | assert_eq!(of("job_1", 1_000), ["g1tsec_a"]); |
| 302 | assert_eq!(of("job_2", 1_000), ["g1tsec_b"]); |
| 303 | assert!(of("job_1", 3_000).is_empty()); |
| 304 | assert_eq!(db.execute(STAND_INS_EXPIRED, params![1_000]).unwrap(), 1); |
| 305 | // Settings rows and jobs carry the new columns. |
| 306 | db.execute("UPDATE settings SET brokered_hosts = '[]'", []).unwrap(); |
| 307 | db.execute("UPDATE jobs SET brokered = 1", []).unwrap(); |
| 308 | } |
| 309 | } |