alien-core 3.3.51

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Non-secret trust and access descriptions for customer-owned GCP federation.

use alien_error::AlienError;
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use url::Url;

use crate::{ErrorData, Result};

/// The exact manager identity trusted by a deployment-owned identity pool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GcpFederationTrust {
    /// OIDC issuer; Google or the manager's Kubernetes issuer.
    pub issuer: String,
    /// Exact immutable Google account ID or Kubernetes service-account subject.
    pub subject: String,
}

impl GcpFederationTrust {
    pub fn validate(&self) -> Result<()> {
        let issuer = Url::parse(&self.issuer)
            .map_err(|_| invalid("issuer", "must be an absolute HTTPS issuer URL"))?;
        if issuer.scheme() != "https"
            || issuer.host_str().is_none()
            || !issuer.username().is_empty()
            || issuer.password().is_some()
            || issuer.query().is_some()
            || issuer.fragment().is_some()
        {
            return Err(invalid(
                "issuer",
                "must be HTTPS without credentials, query or fragment",
            ));
        }
        if self.subject.is_empty()
            || self.subject.len() > 127
            || self.subject.chars().any(char::is_control)
        {
            return Err(invalid(
                "subject",
                "must contain 1–127 bytes without control characters",
            ));
        }
        if self.issuer == "https://accounts.google.com"
            && !self.subject.bytes().all(|byte| byte.is_ascii_digit())
        {
            return Err(invalid(
                "subject",
                "Google trust requires the immutable numeric account ID",
            ));
        }
        Ok(())
    }

    /// CEL equality against the exact subject, with string-literal escaping.
    pub fn subject_condition(&self) -> String {
        format!(
            "assertion.sub == {}",
            serde_json::Value::String(self.subject.clone())
        )
    }
}

/// Setup-owned federation access. Contains no assertions, keys or access tokens.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GcpFederationAccess {
    pub project_number: String,
    pub pool_id: String,
    pub provider_id: String,
    pub service_account_email: String,
    /// Installation- and purpose-specific assertion audience, independently
    /// checked by the manager against its authorized deployment record.
    pub assertion_audience: String,
    pub trust: GcpFederationTrust,
}

impl GcpFederationAccess {
    pub fn validate(&self) -> Result<()> {
        self.trust.validate()?;
        let Some(scope_hash) = self
            .assertion_audience
            .strip_prefix("urn:deployment-access:v1:")
        else {
            return Err(invalid(
                "assertionAudience",
                "must identify an installation-scoped audience",
            ));
        };
        if scope_hash.len() != 64
            || !scope_hash
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        {
            return Err(invalid(
                "assertionAudience",
                "must contain a SHA-256 installation scope",
            ));
        }
        if self.project_number.is_empty()
            || self.project_number.len() > 30
            || !self
                .project_number
                .bytes()
                .all(|byte| byte.is_ascii_digit())
        {
            return Err(invalid("projectNumber", "must be a numeric project number"));
        }
        validate_federation_id("poolId", &self.pool_id)?;
        validate_federation_id("providerId", &self.provider_id)?;
        let Some((account, domain)) = self.service_account_email.split_once('@') else {
            return Err(invalid(
                "serviceAccountEmail",
                "must be a Google service-account email",
            ));
        };
        if account.is_empty()
            || !domain.ends_with(".iam.gserviceaccount.com")
            || !self.service_account_email.bytes().all(|byte| {
                byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"@.-".contains(&byte)
            })
            || domain.contains('@')
        {
            return Err(invalid(
                "serviceAccountEmail",
                "must be a Google service-account email",
            ));
        }
        Ok(())
    }

    /// Validates before constructing the canonical Google STS audience.
    pub fn provider_audience(&self) -> Result<String> {
        self.validate()?;
        Ok(format!("//iam.googleapis.com/projects/{}/locations/global/workloadIdentityPools/{}/providers/{}", self.project_number, self.pool_id, self.provider_id))
    }

    /// Pool-local exact principal; providers do not introduce a subject namespace.
    pub fn principal(&self) -> Result<String> {
        self.validate()?;
        // Encode the subject as one URI path segment, including slashes.
        let mut principal = Url::parse(&format!(
            "https://iam.googleapis.com/projects/{}/locations/global/workloadIdentityPools/{}/subject/",
            self.project_number, self.pool_id
        ))
        .map_err(|_| invalid("projectNumber", "cannot construct principal URI"))?;
        principal
            .path_segments_mut()
            .map_err(|_| invalid("subject", "cannot construct principal URI"))?
            .pop_if_empty()
            .push(&self.trust.subject);
        Ok(principal.as_str().replacen("https://", "principal://", 1))
    }
}

/// Google pool and provider IDs share the same documented restrictions.
pub fn validate_federation_id(field: &str, value: &str) -> Result<()> {
    if !(4..=32).contains(&value.len())
        || value.starts_with("gcp-")
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    {
        return Err(invalid(
            field,
            "must contain 4–32 lowercase letters, digits or hyphens and must not start with gcp-",
        ));
    }
    Ok(())
}

fn invalid(field: &str, reason: &str) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::GcpFederationInvalid {
        field: field.to_string(),
        reason: reason.to_string(),
    })
}

/// Identity of one installation. The runtime constructs this from its
/// authenticated deployment record, never names or imported target metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GcpFederationScope {
    /// Immutable ID allocated by the control plane before cloud setup.
    /// Names, display metadata and imported resource identifiers cannot replace it.
    pub deployment_id: String,
}

impl GcpFederationScope {
    /// Check setup-owned access against the runtime's authenticated installation.
    pub fn validate_access(
        &self,
        access: &GcpFederationAccess,
        resource_type: &crate::ResourceType,
    ) -> Result<()> {
        access.validate()?;
        if access.assertion_audience != self.assertion_audience(resource_type)? {
            return Err(invalid(
                "assertionAudience",
                "does not match the authorized installation and access purpose; rerun setup",
            ));
        }
        Ok(())
    }

    /// Binds an assertion to one immutable installation and access purpose.
    /// Base64 components keep the cross-language hash unambiguous without
    /// depending on JSON escaping rules in setup engines.
    pub fn assertion_audience(&self, resource_type: &crate::ResourceType) -> Result<String> {
        Ok(format!(
            "urn:deployment-access:v1:{}",
            self.scope_hash(resource_type)?
        ))
    }

    /// A fresh installation gets a fresh pool name even while a deleted
    /// installation's pool remains reserved during Google's recovery period.
    pub fn pool_id(&self, resource_type: &crate::ResourceType) -> Result<String> {
        Ok(format!(
            "deployment-{}",
            &self.scope_hash(resource_type)?[..20]
        ))
    }

    fn scope_hash(&self, resource_type: &crate::ResourceType) -> Result<String> {
        if self.deployment_id.is_empty()
            || self.deployment_id.len() > 128
            || !self
                .deployment_id
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte))
        {
            return Err(invalid(
                "scope",
                "requires the immutable registered deployment ID",
            ));
        }
        if resource_type != &crate::RemoteStackManagement::RESOURCE_TYPE
            && resource_type != &crate::RemoteBindings::RESOURCE_TYPE
        {
            return Err(invalid(
                "scope",
                "requires a management or published-resource access purpose",
            ));
        }
        let encoded =
            [self.deployment_id.as_str(), resource_type.as_ref()].map(|part| STANDARD.encode(part));
        let hash = Sha256::digest(format!("gcp-deployment-access-v1:{}", encoded.join(":")));
        Ok(format!("{hash:x}"))
    }
}

/// Trusted manager-local assertion source. Never read this from target setup outputs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "type", deny_unknown_fields)]
pub enum GcpFederationSource {
    /// The container caller uses its existing scoped grant on a linked account.
    GoogleServiceAccount {
        #[cfg_attr(feature = "openapi", schema(value_type = Object))]
        source: Box<crate::GcpClientConfig>,
        service_account_email: String,
        service_account_unique_id: String,
    },
    /// Audience-specific TokenRequest using rotating in-cluster API credentials.
    KubernetesServiceAccount {
        issuer: String,
        api_server: String,
        api_token_file: String,
        ca_file: String,
        namespace: String,
        service_account: String,
    },
}

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

    fn access() -> GcpFederationAccess {
        GcpFederationAccess {
            project_number: "123456789012".to_string(),
            pool_id: "deployment-management".to_string(),
            provider_id: "manager".to_string(),
            service_account_email: "management@example-project.iam.gserviceaccount.com".to_string(),
            assertion_audience: GcpFederationScope {
                deployment_id: "deployment-production".to_string(),
            }
            .assertion_audience(&crate::RemoteStackManagement::RESOURCE_TYPE)
            .unwrap(),
            trust: GcpFederationTrust {
                issuer: "https://accounts.google.com".to_string(),
                subject: "123456789012345678901".to_string(),
            },
        }
    }

    #[test]
    fn broker_rejects_foreign_installation_and_access_purpose() {
        let scope = GcpFederationScope {
            deployment_id: "deployment-production".to_string(),
        };
        let access = access();
        scope
            .validate_access(&access, &crate::RemoteStackManagement::RESOURCE_TYPE)
            .unwrap();
        assert!(scope
            .validate_access(&access, &crate::RemoteBindings::RESOURCE_TYPE)
            .is_err());
        let other = GcpFederationScope {
            deployment_id: "deployment-recreated".to_string(),
        };
        assert!(other
            .validate_access(&access, &crate::RemoteStackManagement::RESOURCE_TYPE)
            .is_err());
        let mut substituted = access.clone();
        substituted.assertion_audience = other
            .assertion_audience(&crate::RemoteStackManagement::RESOURCE_TYPE)
            .unwrap();
        assert!(scope
            .validate_access(&substituted, &crate::RemoteStackManagement::RESOURCE_TYPE)
            .is_err());
    }

    #[test]
    fn invalid_target_identifiers_cannot_construct_google_endpoints() {
        for value in [
            "",
            "../other",
            "123/../456",
            "123?host=other",
            "https://other.invalid",
        ] {
            let mut config = access();
            config.project_number = value.to_string();
            assert!(
                config.provider_audience().is_err(),
                "accepted project {value}"
            );
            assert!(config.principal().is_err());
        }
        for value in [
            "abc",
            "UPPER",
            "gcp-reserved",
            "other/provider",
            "other?query",
            "other#fragment",
        ] {
            let mut config = access();
            config.pool_id = value.to_string();
            assert!(config.provider_audience().is_err(), "accepted pool {value}");
            config = access();
            config.provider_id = value.to_string();
            assert!(
                config.provider_audience().is_err(),
                "accepted provider {value}"
            );
        }
    }

    #[test]
    fn issuer_and_subject_cannot_implicitly_broaden_trust() {
        for issuer in [
            "http://issuer.example",
            "https://user:password@issuer.example",
            "https://issuer.example?x=y",
            "https://issuer.example/#fragment",
        ] {
            let mut config = access();
            config.trust.issuer = issuer.to_string();
            assert!(config.provider_audience().is_err());
        }
        for subject in [
            "",
            "manager@example-project.iam.gserviceaccount.com",
            "123\n456",
        ] {
            let mut config = access();
            config.trust.subject = subject.to_string();
            assert!(config.provider_audience().is_err());
        }
    }

    #[test]
    fn kubernetes_subject_is_exact_and_pool_local() {
        let mut config = access();
        config.trust = GcpFederationTrust {
            issuer: "https://oidc.eks.example/id/cluster".to_string(),
            subject: "system:serviceaccount:runtime:manager".to_string(),
        };
        assert_eq!(config.provider_audience().unwrap(), "//iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/deployment-management/providers/manager");
        assert_eq!(config.principal().unwrap(), "principal://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/deployment-management/subject/system:serviceaccount:runtime:manager");
        assert_eq!(
            config.trust.subject_condition(),
            "assertion.sub == \"system:serviceaccount:runtime:manager\""
        );
        let principal = config.principal().unwrap();
        config.pool_id = "different-deployment".to_string();
        assert_ne!(config.principal().unwrap(), principal);
    }

    #[test]
    fn subject_quotes_cannot_turn_equality_into_a_cel_expression() {
        let mut config = access();
        config.trust.issuer = "https://issuer.example".to_string();
        config.trust.subject = "subject\" || true || assertion.sub == \"other".to_string();
        config.validate().unwrap();
        let condition = config.trust.subject_condition();
        let literal = condition.strip_prefix("assertion.sub == ").unwrap();
        assert_eq!(
            serde_json::from_str::<String>(literal).unwrap(),
            config.trust.subject
        );
    }

    #[test]
    fn immutable_installations_and_access_purposes_have_distinct_audiences() {
        let scope = GcpFederationScope {
            deployment_id: "deployment-original".to_string(),
        };
        let management = &crate::RemoteStackManagement::RESOURCE_TYPE;
        let original = scope.assertion_audience(management).unwrap();
        // Recreating the same logical name allocates a new ID. Old cloud trust
        // cannot be selected by copying an orphaned installation's descriptor.
        let recreated = GcpFederationScope {
            deployment_id: "deployment-recreated".to_string(),
        };
        assert_ne!(original, recreated.assertion_audience(management).unwrap());
        assert_ne!(
            scope.pool_id(management).unwrap(),
            recreated.pool_id(management).unwrap()
        );
        assert_ne!(
            scope.pool_id(management).unwrap(),
            scope
                .pool_id(&crate::RemoteBindings::RESOURCE_TYPE)
                .unwrap()
        );
        assert!(scope.pool_id(management).unwrap().len() <= 32);
        assert_ne!(
            original,
            scope
                .assertion_audience(&crate::RemoteBindings::RESOURCE_TYPE)
                .unwrap()
        );
        for id in [
            "",
            " deployment-original",
            "deployment-original ",
            "other/path",
            "other:namespace",
        ] {
            assert!(GcpFederationScope {
                deployment_id: id.to_string()
            }
            .assertion_audience(management)
            .is_err());
        }
    }

    #[test]
    fn plain_legacy_email_is_not_a_federation_descriptor() {
        assert!(serde_json::from_str::<GcpFederationAccess>(
            "\"management@example-project.iam.gserviceaccount.com\""
        )
        .is_err());
        let mut value = serde_json::to_value(access()).unwrap();
        value["tokenUrl"] = "https://other.invalid".into();
        assert!(serde_json::from_value::<GcpFederationAccess>(value).is_err());
    }
}