OXYGENHUB
# 00ef7b83b340 oxygenhub / crates / hub / src / web / secrets.rs
2.5 KiB · Rust · last changed Secrets for pipelines, mounted as files 1 month ago source blame history raw
1
//! The Flow secrets panel (hub spec §13.2, oxygenhub#107) shared by the
2
//! administration, organisation and repository settings pages: names
3
//! only, values typed once and never shown.
4
5
use crate::auth::Viewer;
6
use crate::db::accounts;
7
use crate::levels::At;
8
use crate::secrets::{self, Seen};
9
use crate::Shared;
10
use serde::Deserialize;
11
12
#[derive(Deserialize)]
13
pub struct SecretForm {
14
    #[serde(rename = "_csrf")]
15
    pub csrf_token: String,
16
    #[serde(default)]
17
    action: String,
18
    #[serde(default)]
19
    name: String,
20
    #[serde(default)]
21
    value: String,
22
}
23
24
pub struct Panel {
25
    pub own: Vec<Seen>,
26
    pub inherited: Vec<Seen>,
27
}
28
29
pub async fn panel(app: &Shared, at: &At) -> sqlx::Result<Panel> {
30
    let (own, inherited): (Vec<_>, Vec<_>) =
31
        secrets::seen(&app.db, at.scope, &at.owner).await?.into_iter().partition(|v| v.from.is_empty());
32
    Ok(Panel { own, inherited })
33
}
34
35
/// Apply the panel's form: `Ok(notice)` or `Err(message for the user)`.
36
pub async fn apply(app: &Shared, viewer: &Viewer, at: &At, f: SecretForm) -> sqlx::Result<Result<String, String>> {
37
    let name = f.name.trim();
38
    if !secrets::name_ok(name) {
39
        return Ok(Err("A secret's name is 1 to 64 of A-Z a-z 0-9 . _ -, as the pipeline's `secret` block names it.".into()));
40
    }
41
    Ok(Ok(match f.action.as_str() {
42
        "set" => {
43
            let value = f.value.replace("\r\n", "\n");
44
            if value.is_empty() {
45
                return Ok(Err("Type the secret's value.".into()));
46
            }
47
            if value.len() > secrets::MAX_VALUE {
48
                return Ok(Err(format!("A value is up to {} bytes.", secrets::MAX_VALUE)));
49
            }
50
            let own = secrets::list(&app.db, at.scope).await?;
51
            if own.len() >= secrets::MAX_PER_LEVEL && !own.iter().any(|s| s.name == name) {
52
                return Ok(Err(format!("Up to {} secrets here.", secrets::MAX_PER_LEVEL)));
53
            }
54
            secrets::set(&app.db, at.scope, name, &app.secret_key.seal(&value)).await?;
55
            accounts::audit(&app.db, viewer.account(), "flow.secret.set", &at.label, name).await.ok();
56
            format!("{name} set.")
57
        }
58
        "delete" => {
59
            if !secrets::delete(&app.db, at.scope, name).await? {
60
                return Ok(Err(format!("There is no secret {name} here.")));
61
            }
62
            accounts::audit(&app.db, viewer.account(), "flow.secret.deleted", &at.label, name).await.ok();
63
            format!("{name} removed.")
64
        }
65
        _ => return Ok(Err("Unknown action.".into())),
66
    }))
67
}