Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
306 linesCodeBlameRaw
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
16use g1t_contracts::actions::{BrokeredSecret, JobCallArgs, STAND_IN_PREFIX};
17use g1t_contracts::time::rfc3339;
18use g1t_contracts::Outcome;
19use g1t_kit::now_ms;
20use g1t_secrets::random_hex;
21use serde::Deserialize;
22use serde_json::{Map, Value};
23use worker::Result;
24use worker::wasm_bindgen::JsValue;
25
26use crate::plan::LOG_INSERT;
27use crate::{Actions, Count, check};
28
29/// The most hosts one brokered secret names.
30pub(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.
33pub(crate) const MIN_VALUE_CHARS: usize = 8;
34
35/// Keeps a job's stand-in: what it stands for, sealed and bound to it.
36pub(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`.
39pub(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.
42pub(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)]
47pub(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)]
55pub(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.
61pub(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.
70pub(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.
95pub(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.
102pub(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)]
108struct StandInRow {
109 stand_in: String,
110 name: String,
111 value: String,
112 hosts: String,
113}
114
115impl 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.
190 pub async fn brokered_secrets(&self, a: JobCallArgs) -> Result<Outcome<Vec<BrokeredSecret>>> {
191 let job = check!(self.job_for_token(&a).await?);
192 Ok(Outcome::Ok(self.stand_ins_of(&job.id).await?))
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use rusqlite::{Connection, params};
199 use serde_json::{Map, Value, json};
200
201 use super::{Broker, STAND_IN_INSERT, STAND_INS_EXPIRED, STAND_INS_OF_JOB, self_hosted_note, stand_in, substitute};
202
203 fn broker(name: &str, value: &str, hosts: &[&str]) -> Broker {
204 Broker { name: name.into(), value: value.into(), hosts: hosts.iter().map(|h| (*h).to_owned()).collect() }
205 }
206
207 fn counter() -> impl FnMut() -> String {
208 let mut n = 0;
209 move || {
210 n += 1;
211 format!("g1tsec_{n}")
212 }
213 }
214
215 #[test]
216 fn stand_ins_are_long_random_tokens() {
217 let one = stand_in();
218 assert!(one.starts_with("g1tsec_"));
219 assert_eq!(one.len(), "g1tsec_".len() + 48);
220 assert!(one["g1tsec_".len()..].chars().all(|c| c.is_ascii_hexdigit()));
221 assert_ne!(one, stand_in());
222 }
223
224 #[test]
225 fn a_brokered_value_never_reaches_the_job() {
226 let mut secrets: Map<String, Value> = json!({
227 "NPM_TOKEN": "npm_realvalue123",
228 "ALSO_NPM": "npm_realvalue123",
229 "BASIC": "me:npm_realvalue123",
230 "PLAIN": "not-brokered-value",
231 })
232 .as_object()
233 .cloned()
234 .unwrap();
235 let made = substitute(&mut secrets, &[broker("NPM_TOKEN", "npm_realvalue123", &["registry.npmjs.org"])], counter());
236 assert_eq!(made.len(), 1);
237 assert_eq!(made[0].stand_in, "g1tsec_1");
238 assert_eq!(made[0].broker.hosts, ["registry.npmjs.org"]);
239 assert_eq!(secrets["NPM_TOKEN"], "g1tsec_1");
240 assert_eq!(secrets["ALSO_NPM"], "g1tsec_1");
241 assert_eq!(secrets["BASIC"], "me:g1tsec_1");
242 assert_eq!(secrets["PLAIN"], "not-brokered-value");
243 assert!(!serde_json::to_string(&secrets).unwrap().contains("npm_realvalue123"));
244 }
245
246 #[test]
247 fn each_secret_gets_its_own_stand_in_and_longer_values_go_first() {
248 let mut secrets: Map<String, Value> =
249 json!({ "SHORT": "abcdefgh", "LONG": "abcdefgh-and-more" }).as_object().cloned().unwrap();
250 let made = substitute(
251 &mut secrets,
252 &[broker("SHORT", "abcdefgh", &["a.example.com"]), broker("LONG", "abcdefgh-and-more", &["b.example.com"])],
253 counter(),
254 );
255 assert_eq!(made.len(), 2);
256 assert_eq!(made[0].broker.name, "LONG");
257 assert_eq!(secrets["LONG"], "g1tsec_1");
258 assert_eq!(secrets["SHORT"], "g1tsec_2");
259 }
260
261 #[test]
262 fn values_too_short_or_not_given_make_no_stand_in() {
263 let mut secrets: Map<String, Value> = json!({ "PIN": "1234" }).as_object().cloned().unwrap();
264 assert!(substitute(&mut secrets, &[broker("PIN", "1234", &["x.example.com"])], counter()).is_empty());
265 assert!(substitute(&mut secrets, &[broker("GONE", "absent-value", &["x.example.com"])], counter()).is_empty());
266 assert_eq!(secrets["PIN"], "1234");
267 }
268
269 #[test]
270 fn the_self_hosted_note_is_a_warning_naming_the_secret() {
271 let note = self_hosted_note("NPM_TOKEN");
272 assert!(note.starts_with("##[warning]NPM_TOKEN"));
273 assert!(note.contains("only on its own machines"));
274 }
275
276 fn database() -> Connection {
277 let db = Connection::open_in_memory().unwrap();
278 for name in ["0001_init.sql", "0019_brokered_secrets.sql"] {
279 let path = format!("{}/migrations/{name}", env!("CARGO_MANIFEST_DIR"));
280 db.execute_batch(&std::fs::read_to_string(path).unwrap()).unwrap();
281 }
282 db
283 }
284
285 #[test]
286 fn a_job_finds_only_its_own_stand_ins_while_they_work() {
287 let db = database();
288 let keep = |stand_in: &str, job: &str, expires: i64| {
289 db.execute(STAND_IN_INSERT, params![stand_in, job, "NPM_TOKEN", "sealed", "[\"registry.npmjs.org\"]", expires]).unwrap()
290 };
291 keep("g1tsec_a", "job_1", 2_000);
292 keep("g1tsec_b", "job_2", 2_000);
293 keep("g1tsec_c", "job_1", 500);
294 let of = |job: &str, now: i64| -> Vec<String> {
295 let mut rows = db.prepare(STAND_INS_OF_JOB).unwrap();
296 rows.query_map(params![job, now], |row| row.get::<_, String>(0)).unwrap().map(Result::unwrap).collect()
297 };
298 assert_eq!(of("job_1", 1_000), ["g1tsec_a"]);
299 assert_eq!(of("job_2", 1_000), ["g1tsec_b"]);
300 assert!(of("job_1", 3_000).is_empty());
301 assert_eq!(db.execute(STAND_INS_EXPIRED, params![1_000]).unwrap(), 1);
302 // Settings rows and jobs carry the new columns.
303 db.execute("UPDATE settings SET brokered_hosts = '[]'", []).unwrap();
304 db.execute("UPDATE jobs SET brokered = 1", []).unwrap();
305 }
306}