OXYGENHUB
# 8eae2f0e255c oxygenhub / crates / hub / src / keyless.rs
16.3 KiB · Rust · last changed Send a keyless agent's grant signer with its certificate (oxygen#134) 11 days ago source blame history raw
1
//! Certificates for short-lived keys (oxygenhub#241, docs/keyless.md,
2
//! Oxygen spec §14.7): the hub vouches, for ten minutes, for a fresh key
3
//! whose holder proves who it is with a credential the hub issued. A Flow
4
//! job asks with its job token; anything else with one of the hub's OIDC
5
//! tokens for the keyless audience. The key signs, then is thrown away:
6
//! nothing long-lived sits on a runner.
7
//!
8
//! An agent asks with a grant token instead (step 5): its owner signed an
9
//! Oxygen grant letting `agent:NAME@ACCOUNT` act for them (spec §14.7),
10
//! and every certificate issued under it carries that grant, so the
11
//! agent's fresh keys sign in the owner's name with nothing kept on disk
12
//! but the token. Revoking the grant stops the certificates.
13
14
use crate::api::ApiError;
15
use crate::{db, Shared};
16
use axum::extract::Path;
17
use axum::extract::State;
18
use axum::http::{HeaderMap, StatusCode};
19
use axum::Json;
20
use oxy_core::cert::{certify_challenge, Certificate, SignedCertificate, SignedGrant};
21
use oxy_core::identity::{verify_challenge, Identity, Scope, Signature};
22
use serde::{Deserialize, Serialize};
23
24
/// How long a certificate lasts.
25
pub const LIFETIME_MS: i64 = 10 * 60 * 1000;
26
/// How far back a certificate starts, for clocks a little behind.
27
const SKEW_MS: i64 = 30 * 1000;
28
/// What an agent holds in place of a key: `oxyagent_` and 32 random bytes.
29
pub const GRANT_TOKEN_PREFIX: &str = "oxyagent_";
30
31
/// The OIDC audience a token must have to be exchanged here.
32
pub fn audience(base_url: &str) -> String {
33
    format!("{}/keyless", base_url.trim_end_matches('/'))
34
}
35
36
#[derive(Deserialize)]
37
pub struct CertifyRequest {
38
    /// The fresh key's identity object, base64.
39
    pub identity: String,
40
    /// The key's signature over `certify_challenge(credential)`, base64 CBOR.
41
    pub proof: String,
42
    /// `changes,refs` and so on.
43
    pub scope: String,
44
}
45
46
#[derive(Serialize)]
47
pub struct CertifyResponse {
48
    /// The signed certificate, base64 (`[certificate, signature]`).
49
    pub certificate: String,
50
    pub subject: String,
51
    pub expires_ms: i64,
52
    /// For an agent's certificate, the identity that signed its grant
53
    /// (base64), so a repository that never saw the owner's current key can
54
    /// check the grant, and pass it on with its push (oxygen#134).
55
    #[serde(skip_serializing_if = "Option::is_none")]
56
    pub grantor_identity: Option<String>,
57
}
58
59
/// Who a credential says its holder is.
60
struct Proven {
61
    subject: String,
62
    claims: Vec<(String, String)>,
63
    /// The credential's own end, which a certificate never outlives.
64
    until_ms: i64,
65
    target: String,
66
    /// The most the certificate may give.
67
    allowed: Scope,
68
    /// The owner's grant the certificate carries, for an agent.
69
    grant: Option<SignedGrant>,
70
}
71
72
fn bad(status: StatusCode, why: impl Into<String>) -> ApiError {
73
    ApiError(status, why.into())
74
}
75
76
/// A running job's token: its repository, bookmark, run and job.
77
async fn job_proof(app: &Shared, token: &str) -> Result<Proven, ApiError> {
78
    let invalid = || bad(StatusCode::UNAUTHORIZED, "this job token is not valid (the job must be running)");
79
    let hash = crate::auth::token_hash(token);
80
    let job = db::flow::job_by_token(&app.db, &hash, crate::flow::JOB_TOKEN_MAX_AGE_MS)
81
        .await
82
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
83
        .ok_or_else(invalid)?;
84
    let run = db::flow::run_by_id(&app.db, job.run_id)
85
        .await
86
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
87
        .ok_or_else(invalid)?;
88
    let repo = db::repos::get_by_id(&app.db, run.repo_id)
89
        .await
90
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
91
        .ok_or_else(invalid)?;
92
    let mut claims = vec![
93
        ("repository".to_string(), format!("{}/{}", repo.owner, repo.name)),
94
        ("bookmark".to_string(), run.bookmark.clone()),
95
        ("run".to_string(), run.number.to_string()),
96
        ("job".to_string(), job.name.clone()),
97
        ("runner".to_string(), job.runner.clone()),
98
    ];
99
    if !job.environment.is_empty() && !job.approved_by.is_empty() {
100
        claims.push(("environment".to_string(), job.environment.clone()));
101
        claims.push(("approved_by".to_string(), job.approved_by.clone()));
102
    }
103
    Ok(Proven {
104
        subject: format!("repo:{}/{}:bookmark:{}", repo.owner, repo.name, run.bookmark),
105
        claims,
106
        until_ms: job.started_ms.unwrap_or(0) + crate::flow::JOB_TOKEN_MAX_AGE_MS,
107
        target: format!("{}/{}", repo.owner, repo.name),
108
        allowed: Scope::CHANGES | Scope::REFS | Scope::SEAL,
109
        grant: None,
110
    })
111
}
112
113
/// One of this hub's OIDC tokens for the keyless audience.
114
async fn oidc_proof(app: &Shared, token: &str, now: i64) -> Result<Proven, ApiError> {
115
    let issuer = app.oidc().await.map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
116
    let aud = audience(app.config.base_url());
117
    let claims = issuer
118
        .verify(token, &aud, now)
119
        .ok_or_else(|| bad(StatusCode::UNAUTHORIZED, format!("the token is not one of this hub's, for audience {aud}, still valid")))?;
120
    let subject = claims["sub"].as_str().unwrap_or("").to_string();
121
    if subject.is_empty() {
122
        return Err(bad(StatusCode::UNAUTHORIZED, "the token names no subject"));
123
    }
124
    let keep = ["repository", "bookmark", "run_number", "job", "runner", "environment", "approved_by"];
125
    let mut out = Vec::new();
126
    for k in keep {
127
        match &claims[k] {
128
            serde_json::Value::String(s) => out.push((k.to_string(), s.clone())),
129
            serde_json::Value::Number(n) => out.push((k.to_string(), n.to_string())),
130
            _ => {}
131
        }
132
    }
133
    Ok(Proven {
134
        target: claims["repository"].as_str().unwrap_or(&subject).to_string(),
135
        subject,
136
        claims: out,
137
        until_ms: claims["exp"].as_i64().unwrap_or(0) * 1000,
138
        allowed: Scope::CHANGES | Scope::REFS | Scope::SEAL,
139
        grant: None,
140
    })
141
}
142
143
/// An agent's grant token: the owner's live grant.
144
async fn grant_proof(app: &Shared, token: &str, now: i64) -> Result<Proven, ApiError> {
145
    let invalid = || bad(StatusCode::UNAUTHORIZED, "this agent grant is not valid (revoked, ended or unknown)");
146
    let g = db::accounts::agent_grant_by_token(&app.db, &crate::auth::token_hash(token))
147
        .await
148
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
149
        .filter(|g| g.live(now))
150
        .ok_or_else(invalid)?;
151
    let signed = SignedGrant::decode(&g.signed).map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
152
    db::accounts::touch_agent_grant(&app.db, g.id).await.ok();
153
    Ok(Proven {
154
        subject: g.subject.clone(),
155
        claims: vec![("agent".to_string(), g.agent.clone()), ("grant".to_string(), g.id.to_string())],
156
        until_ms: g.expires_ms,
157
        target: g.subject,
158
        allowed: signed.grant.scope,
159
        grant: Some(signed),
160
    })
161
}
162
163
/// `POST /api/v1/keyless/certify`: a ten-minute certificate for a fresh
164
/// key, for whoever the bearer credential proves.
165
pub async fn certify(
166
    State(app): State<Shared>,
167
    headers: HeaderMap,
168
    Json(req): Json<CertifyRequest>,
169
) -> Result<Json<CertifyResponse>, ApiError> {
170
    let token = oxy_server::bearer_token(&headers)
171
        .ok_or_else(|| bad(StatusCode::UNAUTHORIZED, "ask with a job token or one of this hub's OIDC tokens as the bearer"))?
172
        .to_string();
173
    let now = db::now_ms();
174
    let proven = if token.starts_with(crate::flow::JOB_TOKEN_PREFIX) {
175
        job_proof(&app, &token).await?
176
    } else if token.starts_with(GRANT_TOKEN_PREFIX) {
177
        grant_proof(&app, &token, now).await?
178
    } else {
179
        oidc_proof(&app, &token, now).await?
180
    };
181
    let decode = |what: &str, b64: &str| {
182
        oxy_core::dsse::base64_decode(b64.trim()).ok_or_else(|| bad(StatusCode::BAD_REQUEST, format!("{what} is not base64")))
183
    };
184
    let identity =
185
        Identity::decode(&decode("identity", &req.identity)?).map_err(|e| bad(StatusCode::BAD_REQUEST, format!("identity: {e}")))?;
186
    let proof = oxy_core::cbor::decode(&decode("proof", &req.proof)?)
187
        .map_err(|e| e.to_string())
188
        .and_then(|v| Signature::from_value(&v).map_err(|e| e.to_string()))
189
        .map_err(|e| bad(StatusCode::BAD_REQUEST, format!("proof: {e}")))?;
190
    verify_challenge(&identity, &proof, &certify_challenge(&token))
191
        .map_err(|e| bad(StatusCode::UNAUTHORIZED, format!("the proof does not show this key's holder asked: {e}")))?;
192
    // What was asked, within what the credential allows (an agent's grant
193
    // may leave out `refs`, say): a key asks for all it might sign.
194
    let asked = Scope::parse(&req.scope).map_err(|e| bad(StatusCode::BAD_REQUEST, e))?;
195
    let scope =
196
        asked.names().into_iter().filter_map(|n| Scope::parse(n).ok()).filter(|s| proven.allowed.has(*s)).fold(Scope::NONE, |a, s| a | s);
197
    if scope.is_empty() {
198
        return Err(bad(StatusCode::FORBIDDEN, format!("{} may be certified for {} only", proven.subject, proven.allowed)));
199
    }
200
    let expires = (now + LIFETIME_MS).min(proven.until_ms);
201
    if expires <= now {
202
        return Err(bad(StatusCode::UNAUTHORIZED, "the credential is about to expire: ask with a fresh one"));
203
    }
204
    let (key, secret) =
205
        crate::keys::load_secret(&app.config.keys_dir()).map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
206
    let cert = Certificate {
207
        key: identity,
208
        issuer: key,
209
        subject: proven.subject.clone(),
210
        claims: proven.claims,
211
        scope,
212
        not_before: (now - SKEW_MS) as u64,
213
        expires: expires as u64,
214
        grant: proven.grant,
215
    };
216
    // The grant's signer, as linked to its account (the grant was checked
217
    // against it when it was made).
218
    let grantor_identity = match &cert.grant {
219
        Some(g) => db::accounts::identity_by_key(&app.db, &g.grant.grantor.to_hex())
220
            .await
221
            .ok()
222
            .flatten()
223
            .map(|l| oxy_core::dsse::base64(&l.object)),
224
        None => None,
225
    };
226
    let signed = SignedCertificate::sign(cert, &app.hub_key.identity, &secret);
227
    let detail = format!("{} for {} until {}", signed.cert.key_id().short(12), proven.subject, expires);
228
    db::accounts::audit(&app.db, None, "keyless.certified", &proven.target, &detail).await.ok();
229
    // Every certificate is logged (#238), as Fulcio's are in Rekor.
230
    crate::tlog::log(
231
        &app,
232
        vec![crate::tlog::Pending {
233
            kind: "certificate",
234
            repo: [0; 16],
235
            repo_row: None,
236
            object: signed.cert.hash(),
237
            signers: vec![app.hub_key.key],
238
        }],
239
    )
240
    .await;
241
    Ok(Json(CertifyResponse {
242
        certificate: oxy_core::dsse::base64(&signed.encode()),
243
        subject: proven.subject,
244
        expires_ms: expires,
245
        grantor_identity,
246
    }))
247
}
248
249
#[derive(Deserialize)]
250
pub struct GrantRequest {
251
    /// The signed Oxygen grant (`[grant, signature]`), base64.
252
    pub grant: String,
253
}
254
255
#[derive(Serialize)]
256
pub struct GrantView {
257
    pub id: i64,
258
    pub agent: String,
259
    pub subject: String,
260
    pub grantor: String,
261
    pub scope: String,
262
    pub created_ms: i64,
263
    pub expires_ms: i64,
264
    pub revoked_ms: Option<i64>,
265
    pub last_used_ms: Option<i64>,
266
    /// Shown once, when the grant is made.
267
    #[serde(skip_serializing_if = "Option::is_none")]
268
    pub token: Option<String>,
269
}
270
271
impl From<db::accounts::AgentGrant> for GrantView {
272
    fn from(g: db::accounts::AgentGrant) -> Self {
273
        GrantView {
274
            id: g.id,
275
            agent: g.agent,
276
            subject: g.subject,
277
            grantor: g.grantor,
278
            scope: g.scope,
279
            created_ms: g.created_ms,
280
            expires_ms: g.expires_ms,
281
            revoked_ms: g.revoked_ms,
282
            last_used_ms: g.last_used_ms,
283
            token: None,
284
        }
285
    }
286
}
287
288
/// The account behind a personal token. A grant needs no token scope:
289
/// what makes it is the owner's signature, by a key linked to the account.
290
async fn owner(app: &Shared, headers: &HeaderMap) -> Result<db::accounts::Account, ApiError> {
291
    let c = crate::api::caller(app, headers).await?;
292
    c.account.ok_or_else(|| bad(StatusCode::UNAUTHORIZED, "a personal access token is required"))
293
}
294
295
/// An agent's name: what follows `agent:` and precedes `@`.
296
fn agent_name_ok(name: &str) -> bool {
297
    !name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
298
}
299
300
/// `POST /api/v1/agents/grants`: keep an owner's signed grant to one of
301
/// their agents and give the agent its token.
302
pub async fn grants_create(
303
    State(app): State<Shared>,
304
    headers: HeaderMap,
305
    Json(req): Json<GrantRequest>,
306
) -> Result<(StatusCode, Json<GrantView>), ApiError> {
307
    let account = owner(&app, &headers).await?;
308
    let bytes = oxy_core::dsse::base64_decode(req.grant.trim()).ok_or_else(|| bad(StatusCode::BAD_REQUEST, "the grant is not base64"))?;
309
    let signed = SignedGrant::decode(&bytes).map_err(|e| bad(StatusCode::BAD_REQUEST, format!("grant: {e}")))?;
310
    let g = &signed.grant;
311
    let suffix = format!("@{}", account.username);
312
    let agent = g
313
        .subject
314
        .strip_prefix("agent:")
315
        .and_then(|r| r.strip_suffix(&suffix))
316
        .filter(|n| agent_name_ok(n))
317
        .ok_or_else(|| bad(StatusCode::BAD_REQUEST, format!("a grant here is for agent:NAME{suffix}, not {}", g.subject)))?
318
        .to_string();
319
    if g.issuer != app.hub_key.key {
320
        return Err(bad(StatusCode::BAD_REQUEST, "the grant names another issuer than this hub's key (/.well-known/oxyhub-key)"));
321
    }
322
    let grantor = g.grantor.to_hex();
323
    let linked = db::accounts::identity_by_key(&app.db, &grantor)
324
        .await
325
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
326
        .filter(|i| i.account_id == account.id)
327
        .ok_or_else(|| bad(StatusCode::FORBIDDEN, format!("key {} is not linked to your account: link it first", g.grantor.short(12))))?;
328
    let identity = Identity::decode(&linked.object).map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
329
    signed.verify(&identity).map_err(|e| bad(StatusCode::BAD_REQUEST, format!("the grant does not verify: {e}")))?;
330
    let now = db::now_ms();
331
    if (g.expires as i64) <= now {
332
        return Err(bad(StatusCode::BAD_REQUEST, "the grant has already ended"));
333
    }
334
    let token = format!("{GRANT_TOKEN_PREFIX}{}", crate::auth::random_hex(32));
335
    let hash = crate::auth::token_hash(&token);
336
    let scope = g.scope.to_string();
337
    let id = db::accounts::create_agent_grant(
338
        &app.db,
339
        db::accounts::NewAgentGrant {
340
            account_id: account.id,
341
            agent: &agent,
342
            subject: &g.subject,
343
            grantor: &grantor,
344
            scope: &scope,
345
            signed: &bytes,
346
            token_hash: &hash,
347
            expires_ms: g.expires as i64,
348
        },
349
    )
350
    .await
351
    .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
352
    db::accounts::audit(&app.db, Some(&account), "agent.granted", &g.subject, &format!("grant {id}, {scope}, until {}", g.expires))
353
        .await
354
        .ok();
355
    Ok((
356
        StatusCode::CREATED,
357
        Json(GrantView {
358
            id,
359
            agent,
360
            subject: g.subject.clone(),
361
            grantor,
362
            scope,
363
            created_ms: now,
364
            expires_ms: g.expires as i64,
365
            revoked_ms: None,
366
            last_used_ms: None,
367
            token: Some(token),
368
        }),
369
    ))
370
}
371
372
/// `GET /api/v1/agents/grants`: the caller's grants, without tokens.
373
pub async fn grants_list(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<GrantView>>, ApiError> {
374
    let account = owner(&app, &headers).await?;
375
    let grants =
376
        db::accounts::agent_grants_of(&app.db, account.id).await.map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
377
    Ok(Json(grants.into_iter().map(GrantView::from).collect()))
378
}
379
380
/// `DELETE /api/v1/agents/grants/{id}`: stop certifying under a grant.
381
pub async fn grants_revoke(State(app): State<Shared>, headers: HeaderMap, Path(id): Path<i64>) -> Result<StatusCode, ApiError> {
382
    let account = owner(&app, &headers).await?;
383
    let done = db::accounts::revoke_agent_grant(&app.db, account.id, id)
384
        .await
385
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
386
    if !done {
387
        return Err(bad(StatusCode::NOT_FOUND, "no such live grant of yours"));
388
    }
389
    db::accounts::audit(&app.db, Some(&account), "agent.revoked", &format!("grant {id}"), "").await.ok();
390
    Ok(StatusCode::NO_CONTENT)
391
}