OXYGENHUB

Coverage / crates/hub/src/keyless.rs 89.3%

283 of 317 lines run, 37 of 122 functions · run #468 on main · run missed

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.
323×
pub fn audience(base_url: &str) -> String {
333×
    format!("{}/keyless", base_url.trim_end_matches('/'))
343×
}
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
726×
fn bad(status: StatusCode, why: impl Into<String>) -> ApiError {
736×
    ApiError(status, why.into())
746×
}
75
76
/// A running job's token: its repository, bookmark, run and job.
776×
async fn job_proof(app: &Shared, token: &str) -> Result<Proven, ApiError> {
786×
    let invalid = || bad(StatusCode::UNAUTHORIZED, "this job token is not valid (the job must be running)");
796×
    let hash = crate::auth::token_hash(token);
806×
    let job = db::flow::job_by_token(&app.db, &hash, crate::flow::JOB_TOKEN_MAX_AGE_MS)
816×
        .await
826×
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
836×
        .ok_or_else(invalid)?;
845×
    let run = db::flow::run_by_id(&app.db, job.run_id)
855×
        .await
865×
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
875×
        .ok_or_else(invalid)?;
885×
    let repo = db::repos::get_by_id(&app.db, run.repo_id)
895×
        .await
905×
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
915×
        .ok_or_else(invalid)?;
925×
    let mut claims = vec![
935×
        ("repository".to_string(), format!("{}/{}", repo.owner, repo.name)),
945×
        ("bookmark".to_string(), run.bookmark.clone()),
955×
        ("run".to_string(), run.number.to_string()),
965×
        ("job".to_string(), job.name.clone()),
975×
        ("runner".to_string(), job.runner.clone()),
98
    ];
995×
    if !job.environment.is_empty() && !job.approved_by.is_empty() {
1000×
        claims.push(("environment".to_string(), job.environment.clone()));
1010×
        claims.push(("approved_by".to_string(), job.approved_by.clone()));
1025×
    }
1035×
    Ok(Proven {
1045×
        subject: format!("repo:{}/{}:bookmark:{}", repo.owner, repo.name, run.bookmark),
1055×
        claims,
1065×
        until_ms: job.started_ms.unwrap_or(0) + crate::flow::JOB_TOKEN_MAX_AGE_MS,
1075×
        target: format!("{}/{}", repo.owner, repo.name),
1085×
        allowed: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1095×
        grant: None,
1105×
    })
1116×
}
112
113
/// One of this hub's OIDC tokens for the keyless audience.
1142×
async fn oidc_proof(app: &Shared, token: &str, now: i64) -> Result<Proven, ApiError> {
1152×
    let issuer = app.oidc().await.map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
1162×
    let aud = audience(app.config.base_url());
1172×
    let claims = issuer
1182×
        .verify(token, &aud, now)
1192×
        .ok_or_else(|| bad(StatusCode::UNAUTHORIZED, format!("the token is not one of this hub's, for audience {aud}, still valid")))?;
1201×
    let subject = claims["sub"].as_str().unwrap_or("").to_string();
1211×
    if subject.is_empty() {
1220×
        return Err(bad(StatusCode::UNAUTHORIZED, "the token names no subject"));
1231×
    }
1241×
    let keep = ["repository", "bookmark", "run_number", "job", "runner", "environment", "approved_by"];
1251×
    let mut out = Vec::new();
1267×
    for k in keep {
1277×
        match &claims[k] {
1280×
            serde_json::Value::String(s) => out.push((k.to_string(), s.clone())),
1290×
            serde_json::Value::Number(n) => out.push((k.to_string(), n.to_string())),
1307×
            _ => {}
131
        }
132
    }
1331×
    Ok(Proven {
1341×
        target: claims["repository"].as_str().unwrap_or(&subject).to_string(),
1351×
        subject,
1361×
        claims: out,
1371×
        until_ms: claims["exp"].as_i64().unwrap_or(0) * 1000,
1381×
        allowed: Scope::CHANGES | Scope::REFS | Scope::SEAL,
1391×
        grant: None,
1401×
    })
1412×
}
142
143
/// An agent's grant token: the owner's live grant.
1442×
async fn grant_proof(app: &Shared, token: &str, now: i64) -> Result<Proven, ApiError> {
1452×
    let invalid = || bad(StatusCode::UNAUTHORIZED, "this agent grant is not valid (revoked, ended or unknown)");
1462×
    let g = db::accounts::agent_grant_by_token(&app.db, &crate::auth::token_hash(token))
1472×
        .await
1482×
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
1492×
        .filter(|g| g.live(now))
1502×
        .ok_or_else(invalid)?;
1512×
    let signed = SignedGrant::decode(&g.signed).map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
1522×
    db::accounts::touch_agent_grant(&app.db, g.id).await.ok();
1532×
    Ok(Proven {
1542×
        subject: g.subject.clone(),
1552×
        claims: vec![("agent".to_string(), g.agent.clone()), ("grant".to_string(), g.id.to_string())],
1562×
        until_ms: g.expires_ms,
1572×
        target: g.subject,
1582×
        allowed: signed.grant.scope,
1592×
        grant: Some(signed),
1602×
    })
1612×
}
162
163
/// `POST /api/v1/keyless/certify`: a ten-minute certificate for a fresh
164
/// key, for whoever the bearer credential proves.
16510×
pub async fn certify(
16610×
    State(app): State<Shared>,
16710×
    headers: HeaderMap,
16810×
    Json(req): Json<CertifyRequest>,
16910×
) -> Result<Json<CertifyResponse>, ApiError> {
17010×
    let token = oxy_server::bearer_token(&headers)
17110×
        .ok_or_else(|| bad(StatusCode::UNAUTHORIZED, "ask with a job token or one of this hub's OIDC tokens as the bearer"))?
17210×
        .to_string();
17310×
    let now = db::now_ms();
17410×
    let proven = if token.starts_with(crate::flow::JOB_TOKEN_PREFIX) {
1756×
        job_proof(&app, &token).await?
1764×
    } else if token.starts_with(GRANT_TOKEN_PREFIX) {
1772×
        grant_proof(&app, &token, now).await?
178
    } else {
1792×
        oidc_proof(&app, &token, now).await?
180
    };
18116×
    let decode = |what: &str, b64: &str| {
18216×
        oxy_core::dsse::base64_decode(b64.trim()).ok_or_else(|| bad(StatusCode::BAD_REQUEST, format!("{what} is not base64")))
18316×
    };
1848×
    let identity =
1858×
        Identity::decode(&decode("identity", &req.identity)?).map_err(|e| bad(StatusCode::BAD_REQUEST, format!("identity: {e}")))?;
1868×
    let proof = oxy_core::cbor::decode(&decode("proof", &req.proof)?)
1878×
        .map_err(|e| e.to_string())
1888×
        .and_then(|v| Signature::from_value(&v).map_err(|e| e.to_string()))
1898×
        .map_err(|e| bad(StatusCode::BAD_REQUEST, format!("proof: {e}")))?;
1908×
    verify_challenge(&identity, &proof, &certify_challenge(&token))
1918×
        .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.
1947×
    let asked = Scope::parse(&req.scope).map_err(|e| bad(StatusCode::BAD_REQUEST, e))?;
1957×
    let scope =
19613×
        asked.names().into_iter().filter_map(|n| Scope::parse(n).ok()).filter(|s| proven.allowed.has(*s)).fold(Scope::NONE, |a, s| a | s);
1977×
    if scope.is_empty() {
1980×
        return Err(bad(StatusCode::FORBIDDEN, format!("{} may be certified for {} only", proven.subject, proven.allowed)));
1997×
    }
2007×
    let expires = (now + LIFETIME_MS).min(proven.until_ms);
2017×
    if expires <= now {
2020×
        return Err(bad(StatusCode::UNAUTHORIZED, "the credential is about to expire: ask with a fresh one"));
2037×
    }
2047×
    let (key, secret) =
2057×
        crate::keys::load_secret(&app.config.keys_dir()).map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
2067×
    let cert = Certificate {
2077×
        key: identity,
2087×
        issuer: key,
2097×
        subject: proven.subject.clone(),
2107×
        claims: proven.claims,
2117×
        scope,
2127×
        not_before: (now - SKEW_MS) as u64,
2137×
        expires: expires as u64,
2147×
        grant: proven.grant,
2157×
    };
216
    // The grant's signer, as linked to its account (the grant was checked
217
    // against it when it was made).
2187×
    let grantor_identity = match &cert.grant {
2192×
        Some(g) => db::accounts::identity_by_key(&app.db, &g.grant.grantor.to_hex())
2202×
            .await
2212×
            .ok()
2222×
            .flatten()
2232×
            .map(|l| oxy_core::dsse::base64(&l.object)),
2245×
        None => None,
225
    };
2267×
    let signed = SignedCertificate::sign(cert, &app.hub_key.identity, &secret);
2277×
    let detail = format!("{} for {} until {}", signed.cert.key_id().short(12), proven.subject, expires);
2287×
    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.
2307×
    crate::tlog::log(
2317×
        &app,
2327×
        vec![crate::tlog::Pending {
2337×
            kind: "certificate",
2347×
            repo: [0; 16],
2357×
            repo_row: None,
2367×
            object: signed.cert.hash(),
2377×
            signers: vec![app.hub_key.key],
2387×
        }],
2397×
    )
2407×
    .await;
2417×
    Ok(Json(CertifyResponse {
2427×
        certificate: oxy_core::dsse::base64(&signed.encode()),
2437×
        subject: proven.subject,
2447×
        expires_ms: expires,
2457×
        grantor_identity,
2467×
    }))
24710×
}
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 {
2721×
    fn from(g: db::accounts::AgentGrant) -> Self {
2731×
        GrantView {
2741×
            id: g.id,
2751×
            agent: g.agent,
2761×
            subject: g.subject,
2771×
            grantor: g.grantor,
2781×
            scope: g.scope,
2791×
            created_ms: g.created_ms,
2801×
            expires_ms: g.expires_ms,
2811×
            revoked_ms: g.revoked_ms,
2821×
            last_used_ms: g.last_used_ms,
2831×
            token: None,
2841×
        }
2851×
    }
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.
2906×
async fn owner(app: &Shared, headers: &HeaderMap) -> Result<db::accounts::Account, ApiError> {
2916×
    let c = crate::api::caller(app, headers).await?;
292
    // Grants are their owner's to make and end, not an agent's.
2936×
    if c.agent {
2941×
        return Err(bad(StatusCode::FORBIDDEN, "an agent's token cannot manage agent grants: use your own"));
2955×
    }
2965×
    c.account.ok_or_else(|| bad(StatusCode::UNAUTHORIZED, "a personal access token is required"))
2976×
}
298
299
/// An agent's name: what follows `agent:` and precedes `@`.
3002×
fn agent_name_ok(name: &str) -> bool {
30112×
    !name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
3022×
}
303
304
/// `POST /api/v1/agents/grants`: keep an owner's signed grant to one of
305
/// their agents and give the agent its token.
3063×
pub async fn grants_create(
3073×
    State(app): State<Shared>,
3083×
    headers: HeaderMap,
3093×
    Json(req): Json<GrantRequest>,
3103×
) -> Result<(StatusCode, Json<GrantView>), ApiError> {
3113×
    let account = owner(&app, &headers).await?;
3123×
    let bytes = oxy_core::dsse::base64_decode(req.grant.trim()).ok_or_else(|| bad(StatusCode::BAD_REQUEST, "the grant is not base64"))?;
3133×
    let signed = SignedGrant::decode(&bytes).map_err(|e| bad(StatusCode::BAD_REQUEST, format!("grant: {e}")))?;
3143×
    let g = &signed.grant;
3153×
    let suffix = format!("@{}", account.username);
3163×
    let agent = g
3173×
        .subject
3183×
        .strip_prefix("agent:")
3193×
        .and_then(|r| r.strip_suffix(&suffix))
3203×
        .filter(|n| agent_name_ok(n))
3213×
        .ok_or_else(|| bad(StatusCode::BAD_REQUEST, format!("a grant here is for agent:NAME{suffix}, not {}", g.subject)))?
3222×
        .to_string();
3232×
    if g.issuer != app.hub_key.key {
3240×
        return Err(bad(StatusCode::BAD_REQUEST, "the grant names another issuer than this hub's key (/.well-known/oxyhub-key)"));
3252×
    }
3262×
    let grantor = g.grantor.to_hex();
3272×
    let linked = db::accounts::identity_by_key(&app.db, &grantor)
3282×
        .await
3292×
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
3302×
        .filter(|i| i.account_id == account.id)
3312×
        .ok_or_else(|| bad(StatusCode::FORBIDDEN, format!("key {} is not linked to your account: link it first", g.grantor.short(12))))?;
3321×
    let identity = Identity::decode(&linked.object).map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
3331×
    signed.verify(&identity).map_err(|e| bad(StatusCode::BAD_REQUEST, format!("the grant does not verify: {e}")))?;
3341×
    let now = db::now_ms();
3351×
    if (g.expires as i64) <= now {
3360×
        return Err(bad(StatusCode::BAD_REQUEST, "the grant has already ended"));
3371×
    }
3381×
    let token = format!("{GRANT_TOKEN_PREFIX}{}", crate::auth::random_hex(32));
3391×
    let hash = crate::auth::token_hash(&token);
3401×
    let scope = g.scope.to_string();
3411×
    let id = db::accounts::create_agent_grant(
3421×
        &app.db,
3431×
        db::accounts::NewAgentGrant {
3441×
            account_id: account.id,
3451×
            agent: &agent,
3461×
            subject: &g.subject,
3471×
            grantor: &grantor,
3481×
            scope: &scope,
3491×
            signed: &bytes,
3501×
            token_hash: &hash,
3511×
            expires_ms: g.expires as i64,
3521×
        },
3531×
    )
3541×
    .await
3551×
    .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
3561×
    db::accounts::audit(&app.db, Some(&account), "agent.granted", &g.subject, &format!("grant {id}, {scope}, until {}", g.expires))
3571×
        .await
3581×
        .ok();
3591×
    Ok((
3601×
        StatusCode::CREATED,
3611×
        Json(GrantView {
3621×
            id,
3631×
            agent,
3641×
            subject: g.subject.clone(),
3651×
            grantor,
3661×
            scope,
3671×
            created_ms: now,
3681×
            expires_ms: g.expires as i64,
3691×
            revoked_ms: None,
3701×
            last_used_ms: None,
3711×
            token: Some(token),
3721×
        }),
3731×
    ))
3743×
}
375
376
/// `GET /api/v1/agents/grants`: the caller's grants, without tokens.
3772×
pub async fn grants_list(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<GrantView>>, ApiError> {
3782×
    let account = owner(&app, &headers).await?;
3791×
    let grants =
3801×
        db::accounts::agent_grants_of(&app.db, account.id).await.map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
3811×
    Ok(Json(grants.into_iter().map(GrantView::from).collect()))
3822×
}
383
384
/// `DELETE /api/v1/agents/grants/{id}`: stop certifying under a grant.
3851×
pub async fn grants_revoke(State(app): State<Shared>, headers: HeaderMap, Path(id): Path<i64>) -> Result<StatusCode, ApiError> {
3861×
    let account = owner(&app, &headers).await?;
3871×
    let done = db::accounts::revoke_agent_grant(&app.db, account.id, id)
3881×
        .await
3891×
        .map_err(|e| bad(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
3901×
    if !done {
3910×
        return Err(bad(StatusCode::NOT_FOUND, "no such live grant of yours"));
3921×
    }
3931×
    db::accounts::audit(&app.db, Some(&account), "agent.revoked", &format!("grant {id}"), "").await.ok();
3941×
    Ok(StatusCode::NO_CONTENT)
3951×
}