|
| 1 | +use diesel::deserialize::{self, FromSql}; |
| 2 | +use diesel::pg::{Pg, PgValue}; |
| 3 | +use diesel::serialize::{self, Output, ToSql}; |
| 4 | +use diesel::sql_types::Jsonb; |
| 5 | +use diesel::{AsExpression, FromSqlRow}; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | + |
| 8 | +/// Data structure containing trusted publisher information extracted from JWT claims |
| 9 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FromSqlRow, AsExpression)] |
| 10 | +#[diesel(sql_type = Jsonb)] |
| 11 | +#[serde(tag = "provider")] |
| 12 | +pub enum TrustpubData { |
| 13 | + #[serde(rename = "github")] |
| 14 | + GitHub { |
| 15 | + /// Repository (e.g. "octo-org/octo-repo") |
| 16 | + repository: String, |
| 17 | + /// Workflow run ID |
| 18 | + run_id: String, |
| 19 | + /// SHA of the commit |
| 20 | + sha: String, |
| 21 | + }, |
| 22 | +} |
| 23 | + |
| 24 | +impl ToSql<Jsonb, Pg> for TrustpubData { |
| 25 | + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result { |
| 26 | + let json = serde_json::to_value(self)?; |
| 27 | + <serde_json::Value as ToSql<Jsonb, Pg>>::to_sql(&json, &mut out.reborrow()) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +impl FromSql<Jsonb, Pg> for TrustpubData { |
| 32 | + fn from_sql(bytes: PgValue<'_>) -> deserialize::Result<Self> { |
| 33 | + let json = <serde_json::Value as FromSql<Jsonb, Pg>>::from_sql(bytes)?; |
| 34 | + Ok(serde_json::from_value(json)?) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +#[cfg(test)] |
| 39 | +mod tests { |
| 40 | + use super::*; |
| 41 | + use insta::assert_json_snapshot; |
| 42 | + |
| 43 | + #[test] |
| 44 | + fn test_serialization() { |
| 45 | + let data = TrustpubData::GitHub { |
| 46 | + repository: "octo-org/octo-repo".to_string(), |
| 47 | + run_id: "example-run-id".to_string(), |
| 48 | + sha: "example-sha".to_string(), |
| 49 | + }; |
| 50 | + |
| 51 | + assert_json_snapshot!(data, @r#" |
| 52 | + { |
| 53 | + "provider": "github", |
| 54 | + "repository": "octo-org/octo-repo", |
| 55 | + "run_id": "example-run-id", |
| 56 | + "sha": "example-sha" |
| 57 | + } |
| 58 | + "#); |
| 59 | + } |
| 60 | +} |
0 commit comments