1
//! Publishing an artifact to object storage, and reading one back.
2
//!
3
//! `s3cmd` stays an external program — it is the credential-handling tool the
4
//! platform already provides — but *what* gets published, under which key, and
5
//! with which provenance is decided by [`crate::artifact`], in one place.
6

            
7
use std::io::Write;
8
use std::path::{Path, PathBuf};
9

            
10
use crate::watchdog::{Termination, run_supervised};
11
use anyhow::{Context, Result, bail};
12
use sha2::{Digest, Sha256};
13

            
14
use crate::artifact::{Identity, Kind, Meta};
15

            
16
/// Credentials and endpoint for the artifacts bucket.
17
pub struct Store {
18
    access_key: String,
19
    secret_key: String,
20
    bucket: String,
21
    endpoint: String,
22
}
23

            
24
impl Store {
25
    /// Reads the bucket configuration, failing closed.
26
    ///
27
    /// Only ever called on a branch where the workflow decided this run may
28
    /// hold the write key; a PR run builds and verifies everything and never
29
    /// reaches here.
30
    pub fn from_env() -> Result<Self> {
31
        let get = |key: &str| -> Result<String> {
32
            let value = std::env::var(key).unwrap_or_default();
33
            if value.is_empty() {
34
                bail!("{key} is required to publish artifacts");
35
            }
36
            Ok(value)
37
        };
38
        Ok(Self {
39
            access_key: get("ARTIFACTS_ACCESS_KEY_ID")?,
40
            secret_key: get("ARTIFACTS_SECRET_ACCESS_KEY")?,
41
            bucket: get("ARTIFACTS_BUCKET")?,
42
            endpoint: get("ARTIFACTS_ENDPOINT")?,
43
        })
44
    }
45

            
46
    fn s3(&self, args: &[&str]) -> Result<()> {
47
        self.run_s3("s3cmd", args)
48
    }
49

            
50
    /// Credentials go in a private config file, never in argv: argv is printed
51
    /// on failure and readable from /proc.
52
1
    fn run_s3(&self, program: &str, args: &[&str]) -> Result<()> {
53
1
        let mut config = tempfile::NamedTempFile::new().context("cannot make the s3cmd config")?;
54
1
        writeln!(
55
1
            config,
56
1
            "[default]\naccess_key = {}\nsecret_key = {}\nhost_base = {}\nhost_bucket = %(bucket)s.{}",
57
1
            self.access_key, self.secret_key, self.endpoint, self.endpoint
58
1
        )
59
1
        .context("cannot write the s3cmd config")?;
60
1
        let mut full = vec![format!("--config={}", config.path().display())];
61
1
        full.extend(args.iter().map(ToString::to_string));
62
1
        run_supervised(program, &full, &[], &Termination::watch()?).context("s3cmd failed")
63
1
    }
64

            
65
    /// Uploads a payload under its content-addressed key, then the meta that
66
    /// points at it, then for coverage the `latest` copy deploy reads. Order
67
    /// matters: a meta must never name an object that is not there yet, since a
68
    /// reader that sees the meta will go fetch it.
69
    pub fn publish(&self, kind: Kind, tarball: &Path, identity: &Identity) -> Result<Meta> {
70
        let meta = Meta {
71
            kind,
72
            sha256: sha256_of(tarball)?,
73
            bytes: std::fs::metadata(tarball)
74
                .with_context(|| format!("cannot stat {}", tarball.display()))?
75
                .len(),
76
            identity: identity.clone(),
77
        };
78

            
79
        let prefix = identity.prefix(&self.bucket);
80
        let object = format!("{prefix}/{}", meta.object_key());
81
        println!(">> publishing {} -> {object}", tarball.display());
82
        self.s3(&["put", &tarball.to_string_lossy(), &object])?;
83

            
84
        let meta_path = tarball.with_extension("meta");
85
        std::fs::write(&meta_path, meta.to_text())
86
            .with_context(|| format!("cannot write {}", meta_path.display()))?;
87
        self.s3(&[
88
            "put",
89
            &meta_path.to_string_lossy(),
90
            &format!("{prefix}/{}", Meta::meta_key(kind)),
91
        ])?;
92
        if kind == Kind::Coverage {
93
            self.s3(&[
94
                "put",
95
                &meta_path.to_string_lossy(),
96
                &format!("s3://{}/{}", self.bucket, Meta::latest_key(kind)),
97
            ])?;
98
        }
99

            
100
        Ok(meta)
101
    }
102
}
103

            
104
/// The hash that becomes part of the object key.
105
///
106
/// Hex-encoded lowercase, so it is the same string `sha256sum` prints — the
107
/// deploy container verifies with that, and a mismatch in encoding would be a
108
/// confusing way to discover it.
109
pub fn sha256_of(path: &Path) -> Result<String> {
110
    use std::io::Read;
111

            
112
    let mut file =
113
        std::fs::File::open(path).with_context(|| format!("cannot open {}", path.display()))?;
114
    let mut hasher = Sha256::new();
115
    let mut buffer = vec![0u8; 64 * 1024];
116
    loop {
117
        let read = file
118
            .read(&mut buffer)
119
            .with_context(|| format!("cannot read {}", path.display()))?;
120
        if read == 0 {
121
            break;
122
        }
123
        hasher.update(&buffer[..read]);
124
    }
125
    Ok(hasher
126
        .finalize()
127
        .iter()
128
        .fold(String::with_capacity(64), |mut hex, byte| {
129
            use std::fmt::Write;
130
            let _ = write!(hex, "{byte:02x}");
131
            hex
132
        }))
133
}
134

            
135
impl Store {
136
    fn s3_get(&self, remote: &str, local: &Path) -> Result<()> {
137
        self.s3(&["--force", "get", remote, &local.to_string_lossy()])
138
    }
139

            
140
    /// Reads one kind's meta out of a run's prefix.
141
    pub fn fetch_meta(&self, kind: Kind, identity: &Identity, into: &Path) -> Result<Meta> {
142
        let remote = format!("{}/{}", identity.prefix(&self.bucket), Meta::meta_key(kind));
143
        let local = into.join(Meta::meta_key(kind));
144
        self.s3_get(&remote, &local)
145
            .with_context(|| format!("no {kind} meta at {remote} — did that job publish?"))?;
146
        let text = std::fs::read_to_string(&local)
147
            .with_context(|| format!("cannot read {}", local.display()))?;
148
        Meta::from_text(&text).with_context(|| format!("malformed {kind} meta"))
149
    }
150

            
151
    /// Downloads a payload and checks it against what its meta claims.
152
    ///
153
    /// The key is content-addressed, so bytes cannot change under a name — but
154
    /// verifying on read is what turns that from an argument into a check.
155
    pub fn verify_object(&self, meta: &Meta, identity: &Identity, into: &Path) -> Result<PathBuf> {
156
        let remote = format!("{}/{}", identity.prefix(&self.bucket), meta.object_key());
157
        let local = into.join(meta.object_key());
158
        self.s3_get(&remote, &local)?;
159

            
160
        let bytes = std::fs::metadata(&local)
161
            .with_context(|| format!("cannot stat {}", local.display()))?
162
            .len();
163
        if bytes != meta.bytes {
164
            bail!(
165
                "{} is {bytes} bytes, its meta says {}",
166
                meta.object_key(),
167
                meta.bytes
168
            );
169
        }
170
        let sha256 = sha256_of(&local)?;
171
        if sha256 != meta.sha256 {
172
            bail!(
173
                "{} hashes to {sha256}, its meta says {}",
174
                meta.object_key(),
175
                meta.sha256
176
            );
177
        }
178
        Ok(local)
179
    }
180

            
181
    /// Writes the manifest. Only finalize calls this, and only after the
182
    /// release has been fetched and verified — the manifest existing is the
183
    /// signal that this run's deployable artifact is complete.
184
    pub fn write_manifest(&self, metas: &[Meta], identity: &Identity, from: &Path) -> Result<()> {
185
        let entries: Vec<serde_json::Value> = metas
186
            .iter()
187
            .map(|meta| {
188
                serde_json::json!({
189
                    "kind": meta.kind.as_str(),
190
                    "object": meta.object_key(),
191
                    "sha256": meta.sha256,
192
                    "bytes": meta.bytes,
193
                    "run_attempt": meta.identity.run_attempt,
194
                })
195
            })
196
            .collect();
197
        let manifest = serde_json::json!({
198
            "commit": identity.commit,
199
            "run_id": identity.run_id,
200
            "builder": identity.builder,
201
            "artifacts": entries,
202
        });
203

            
204
        let local = from.join(crate::artifact::MANIFEST_NAME);
205
        std::fs::write(&local, serde_json::to_vec_pretty(&manifest)?)
206
            .with_context(|| format!("cannot write {}", local.display()))?;
207
        self.s3(&[
208
            "put",
209
            &local.to_string_lossy(),
210
            &format!(
211
                "{}/{}",
212
                identity.prefix(&self.bucket),
213
                crate::artifact::MANIFEST_NAME
214
            ),
215
        ])
216
    }
217
}
218

            
219
#[cfg(test)]
220
mod tests;