1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

use crate::schema::WebcPackageIdentifierV1;

use super::DeploymentV1;
use uuid::Uuid;

/// Basic JWT claims.
///
/// Only default fields.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub struct BaseClaims {
    /// Expiration time.
    #[serde(with = "time::serde::timestamp")]
    pub exp: OffsetDateTime,

    /// Issued at.
    #[serde(with = "time::serde::timestamp")]
    pub iat: OffsetDateTime,

    /// Subject (aka user id)
    pub sub: String,
}

/// Claims for a JWT token that allows running a specific workload on Deploy.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, schemars::JsonSchema)]
pub struct DeployWorkloadTokenV1 {
    /// Expiration time.
    #[serde(with = "time::serde::timestamp")]
    #[schemars(with = "u64")]
    pub exp: OffsetDateTime,

    /// Issued at.
    #[serde(with = "time::serde::timestamp")]
    #[schemars(with = "u64")]
    pub iat: OffsetDateTime,

    /// Subject (aka user id)
    pub sub: String,

    /// jti (aka token id)
    ///
    /// This is a unique identifier for the token.
    /// This can be optional
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<Uuid>,

    /// Deployment configuration from the backend.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cfg: Option<DeploymentConfig>,

    /// Inline deployment configuration used in dynamically created tokens.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployment: Option<DeploymentV1>,

    /// A manually specified webc.
    ///
    /// Note that usually this will be empty, and provided via [`Self::cfg::webc`] instead,
    /// since deployment configs are the common way to specify configurations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webc: Option<WebcPackageIdentifierV1>,

    /// Packages that this deployment is allowed to use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_packages: Option<Vec<WebcPackageIdentifierV1>>,
}

impl DeployWorkloadTokenV1 {
    /// Build the network ID that this workload will connect to
    ///
    pub fn network_id(&self) -> Option<Uuid> {
        self.deployment
            .iter()
            .flat_map(|d| d.workload.capabilities.network.as_ref())
            .flat_map(|n| n.network_id)
            .next()
    }
}

/// A deployment configuration sourced from some a backend storage system.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, schemars::JsonSchema)]
pub struct DeploymentConfig {
    pub backend_url: url::Url,

    /// Unique id for the deployment configuration.
    pub uid: String,

    /// App version id assigned by the backend.
    pub backend_app_version_id: Option<String>,
}

/// Claims for a JWT token that allows running a specific workload on Deploy.
///
/// Can represent different versions of the token.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
// untagged means try each variant, one by one.
// Order is important! Newest versions should be on top.
#[serde(untagged)]
pub enum DeployWorkloadTokenData {
    V1(DeployWorkloadTokenV1),
}

impl From<DeployWorkloadTokenV1> for DeployWorkloadTokenData {
    fn from(value: DeployWorkloadTokenV1) -> Self {
        Self::V1(value)
    }
}

/// Claims for a JWT token that allows running a specific workload on Deploy.
///
/// Can represent different versions of the token.
#[derive(PartialEq, Eq, Clone, Debug, Serialize)]
// untagged means try each variant, one by one.
// Order is important! Newest versions should be on top.
pub struct DeployWorkloadToken {
    /// Raw JWT token.
    pub raw: String,
    /// Claims data extracted from the token.
    pub data: DeployWorkloadTokenData,
}

impl DeployWorkloadTokenData {
    pub fn expires(&self) -> Option<&OffsetDateTime> {
        match self {
            DeployWorkloadTokenData::V1(v1) => Some(&v1.exp),
        }
    }

    pub fn issued_at(&self) -> &OffsetDateTime {
        match self {
            DeployWorkloadTokenData::V1(v1) => &v1.iat,
        }
    }

    pub fn subject(&self) -> &str {
        match self {
            DeployWorkloadTokenData::V1(v1) => &v1.sub,
        }
    }

    /// Direct webc spec for this workload.
    ///
    /// Note: do not confuse this witht he DeploymentConfig webc, which is
    /// available on [`Self::cfg`].
    pub fn webc_spec(&self) -> Option<&WebcPackageIdentifierV1> {
        match self {
            Self::V1(v1) => v1.webc.as_ref(),
        }
    }

    pub fn deployment_config(&self) -> Option<&DeploymentConfig> {
        match self {
            Self::V1(v) => v.cfg.as_ref(),
        }
    }

    pub fn jti(&self) -> Option<&Uuid> {
        match self {
            Self::V1(v) => v.jti.as_ref(),
        }
    }

    pub fn has_webc_spec(&self) -> bool {
        self.webc_spec().is_some()
    }

    pub fn network_id(&self) -> Option<Uuid> {
        match self {
            DeployWorkloadTokenData::V1(v1) => v1.network_id(),
        }
    }

    pub fn as_v1(&self) -> Option<&DeployWorkloadTokenV1> {
        match &self {
            DeployWorkloadTokenData::V1(x) => Some(x),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_deser_tokens() {
        #[allow(deprecated)]
        let expected = DeployWorkloadTokenData::V1(DeployWorkloadTokenV1 {
            exp: OffsetDateTime::from_unix_timestamp(10000).unwrap(),
            iat: OffsetDateTime::from_unix_timestamp(20000).unwrap(),
            sub: "user-1".to_string(),
            jti: None,
            deployment: None,
            cfg: Some(DeploymentConfig {
                backend_url: "http://test.com".parse().unwrap(),
                uid: "123".to_string(),
                backend_app_version_id: None,
            }),
            webc: Some(WebcPackageIdentifierV1 {
                repository: Some("https://registry.wapm.dev".parse().unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: Some("1.2.3".to_string()),
            }),
            allowed_packages: Some(vec![WebcPackageIdentifierV1 {
                repository: Some("https://registry.wapm.dev".parse().unwrap()),
                namespace: "ns".to_string(),
                name: "name".to_string(),
                tag: Some("1.2.3".to_string()),
            }]),
        });

        let raw = r#"
{
  "exp": 10000,
  "iat": 20000,
  "sub": "user-1",
  "webc": {
    "repository": "https://registry.wapm.dev/",
    "namespace": "ns",
    "name": "name",
    "tag": "1.2.3",
    "hash": null,
    "download_url": "https://test.com/lala"
  },
  "cfg": {
    "uid": "123",
    "backend_url": "http://test.com"
  },
  "allowed_packages": [
    {
      "repository": "https://registry.wapm.dev/",
      "namespace": "ns",
      "name": "name",
      "tag": "1.2.3",
      "hash": null,
      "download_url": "https://test.com/lala"
    }
  ]
}
"#;

        let deser: DeployWorkloadTokenData =
            crate::schema::deserialize_json(raw.as_bytes()).unwrap();
        assert_eq!(
            deser
                .webc_spec()
                .unwrap()
                .build_download_url()
                .unwrap()
                .to_string(),
            "https://registry.wapm.dev/ns/name@1.2.3",
        );
        pretty_assertions::assert_eq!(deser, expected);
    }
}