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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! Distro/OS release source for `rpm`, `deb`, and `apk` purls.
//!
//! Version and EOL data comes from a curated RHEL lifecycle table, the public
//! Red Hat Product Life Cycle API, and endoflife.date (v1 product and product
//! list endpoints). Channels are `X` and versions are `X.Y`; channel text has
//! dots replaced by hyphens because release channels cannot contain dots.
//!
//! RHEL/UBI artifacts are the public OCI manifest at
//! `registry.access.redhat.com/v2/ubi{major}/ubi/manifests/{stream}`. The
//! registry digest is the artifact hash and the digest URL is the artifact URL.
//! No subscription artifact is fabricated; an authenticated registry (401/403)
//! produces [`UnsupportedReason::Unavailable`] so callers emit version labels
//! only. Distro builds not published as UBI return [`UnsupportedReason::NoArtifacts`].
//!
//! [`ManifestHttp`] is a separate seam from [`RegistryHttp`] because the OCI
//! index fetch needs an `Accept` header and the returned digest header, which
//! the shared registry transport does not expose.
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::sync::Arc;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::release::http::{HTTP_TIMEOUT, RegistryHttp, USER_AGENT};
use crate::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
VersionInfo,
};
pub const DEFAULT_ENDOFLIFE_BASE_URL: &str = "https://endoflife.date/api/v1";
pub const DEFAULT_RHEL_LIFECYCLE_URL: &str = "https://access.redhat.com/product-life-cycles/api/v1/products?name=Red%20Hat%20Enterprise%20Linux";
pub const DEFAULT_REGISTRY_BASE_URL: &str = "https://registry.access.redhat.com";
pub const OCI_INDEX_ACCEPT: &str = "application/vnd.oci.image.index.v1+json";
/// Canonical project slug for every Red Hat Enterprise Linux variant.
pub const RHEL_PROJECT: &str = "red-hat-enterprise-linux";
/// Curated RHEL major channels. Point releases always come from lifecycle data.
pub const RHEL_MAJORS: &[&str] = &["6", "7", "8", "9", "10"];
/// Edition tokens that become channel suffixes.
pub const RHEL_EDITIONS: &[&str] = &[
"eus",
"aus",
"tus",
"sap",
"els",
"rt",
"nfv",
"av",
"crb",
"desktop",
"workstation",
"hpc",
];
/// Architecture tokens that append to a channel. `x86_64` is the default and is
/// intentionally absent.
pub const RHEL_ARCHES: &[&str] = &["aarch64", "ppc64le", "ppc64", "s390x"];
/// One curated RHEL channel. `eol` is the published lifecycle end date; API
/// data replaces it when available.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CuratedChannel {
pub major: &'static str,
pub edition: Option<&'static str>,
pub eol: Option<&'static str>,
}
/// Curated majors plus the edition channels the canonical identity model
/// expects (`6-els`, `8-eus`, ...). Point versions are deliberately absent:
/// they are only emitted when lifecycle data supplies them.
pub const RHEL_CURATED_CHANNELS: &[CuratedChannel] = &[
CuratedChannel {
major: "6",
edition: None,
eol: Some("2020-11-30"),
},
CuratedChannel {
major: "6",
edition: Some("els"),
eol: Some("2024-06-30"),
},
CuratedChannel {
major: "7",
edition: None,
eol: Some("2024-06-30"),
},
CuratedChannel {
major: "7",
edition: Some("els"),
eol: Some("2026-06-30"),
},
CuratedChannel {
major: "8",
edition: None,
eol: Some("2029-05-31"),
},
CuratedChannel {
major: "8",
edition: Some("eus"),
eol: Some("2029-05-31"),
},
CuratedChannel {
major: "9",
edition: None,
eol: Some("2032-05-31"),
},
CuratedChannel {
major: "9",
edition: Some("eus"),
eol: Some("2032-05-31"),
},
CuratedChannel {
major: "10",
edition: None,
eol: Some("2035-05-31"),
},
];
/// Compose a channel name, replacing dots because the release channel rkey
/// grammar forbids them.
pub fn distro_channel(major: &str, edition: Option<&str>, arch: Option<&str>) -> String {
[Some(major), edition, arch]
.into_iter()
.flatten()
.map(|part| part.trim().replace('.', "-"))
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join("-")
}
/// One lifecycle channel or version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LifecycleEntry {
pub channel: String,
pub version: Option<String>,
pub eol: Option<String>,
}
/// A recognized distro/OS product.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DistroProject {
pub project: &'static str,
pub vendor: &'static str,
pub product: &'static str,
pub lifecycle_url: &'static str,
/// endoflife.date product slug, when the product is published there.
pub product_slug: Option<&'static str>,
pub rhel: bool,
}
const RHEL: DistroProject = DistroProject {
project: RHEL_PROJECT,
vendor: "Red Hat",
product: "Red Hat Enterprise Linux",
lifecycle_url: "https://access.redhat.com/product-life-cycles?product=Red%20Hat%20Enterprise%20Linux",
product_slug: Some(RHEL_PROJECT),
rhel: true,
};
const DEBIAN: DistroProject = DistroProject {
project: "debian",
vendor: "Debian",
product: "Debian",
lifecycle_url: "https://endoflife.date/debian",
product_slug: Some("debian"),
rhel: false,
};
const UBUNTU: DistroProject = DistroProject {
project: "ubuntu",
vendor: "Canonical",
product: "Ubuntu",
lifecycle_url: "https://endoflife.date/ubuntu",
product_slug: Some("ubuntu"),
rhel: false,
};
const ALPINE: DistroProject = DistroProject {
project: "alpine-linux",
vendor: "Alpine Linux",
product: "Alpine Linux",
lifecycle_url: "https://endoflife.date/alpine-linux",
// The purl namespace says `alpine`; the all-products endpoint resolves
// that alias to the canonical `alpine-linux` product slug.
product_slug: Some("alpine"),
rhel: false,
};
const FEDORA: DistroProject = DistroProject {
project: "fedora",
vendor: "Fedora Project",
product: "Fedora Linux",
lifecycle_url: "https://endoflife.date/fedora",
product_slug: Some("fedora"),
rhel: false,
};
const CENTOS_STREAM: DistroProject = DistroProject {
project: "centos-stream",
vendor: "CentOS",
product: "CentOS Stream",
lifecycle_url: "https://endoflife.date/centos-stream",
product_slug: Some("centos-stream"),
rhel: false,
};
const ORACLE_LINUX: DistroProject = DistroProject {
project: "oracle-linux",
vendor: "Oracle",
product: "Oracle Linux",
lifecycle_url: "https://endoflife.date/oracle-linux",
product_slug: Some("oracle-linux"),
rhel: false,
};
const AMAZON_LINUX: DistroProject = DistroProject {
project: "amazon-linux",
vendor: "Amazon",
product: "Amazon Linux",
lifecycle_url: "https://endoflife.date/amazon-linux",
product_slug: Some("amazon-linux"),
rhel: false,
};
/// Resolve a purl to an OS product. Package-level distro purls (`openssl`,
/// `kernel`, ...) are intentionally not recognized: their lifecycle is not the
/// distro lifecycle.
pub fn resolve_project(project: &ProjectRef) -> Option<DistroProject> {
let (purl_type, namespace, name) = purl_parts(project);
match purl_type.as_str() {
"rpm" => match (namespace.as_str(), name.as_str()) {
("redhat", "enterprise_linux" | "enterprise-linux" | "rhel" | "rhel_els")
| ("", "enterprise_linux" | "enterprise-linux" | "redhat-enterprise-linux") => {
Some(RHEL)
}
("fedora", "fedora") => Some(FEDORA),
("centos", "centos" | "centos-stream") => Some(CENTOS_STREAM),
("oracle", "oracle_linux" | "oracle-linux") => Some(ORACLE_LINUX),
("amazon", "amazon_linux" | "amazon-linux") => Some(AMAZON_LINUX),
_ => None,
},
"deb" => match name.as_str() {
"debian" => Some(DEBIAN),
"ubuntu" => Some(UBUNTU),
_ => None,
},
"apk" => match name.as_str() {
"alpine" | "alpine-linux" => Some(ALPINE),
_ => None,
},
_ => None,
}
}
/// Distro purl types this source answers for.
pub fn is_distro_purl_type(purl_type: &str) -> bool {
matches!(
purl_type.trim().to_ascii_lowercase().as_str(),
"rpm" | "deb" | "apk"
)
}
fn purl_parts(project: &ProjectRef) -> (String, String, String) {
let purl_type = project.purl_type.trim().to_ascii_lowercase();
let raw = project.purl.trim();
let raw = raw.strip_prefix("pkg:").unwrap_or(raw);
let raw = raw.split(['?', '#']).next().unwrap_or(raw);
let raw = raw.split('@').next().unwrap_or(raw);
let mut segments: Vec<&str> = raw.split('/').filter(|part| !part.is_empty()).collect();
if segments
.first()
.is_some_and(|first| first.eq_ignore_ascii_case(&purl_type))
{
segments.remove(0);
}
if segments.is_empty() {
return match project.name.trim().split_once('/') {
Some((namespace, name)) => (
purl_type,
namespace.trim().to_ascii_lowercase(),
name.trim().to_ascii_lowercase(),
),
None => (
purl_type,
String::new(),
project.name.trim().to_ascii_lowercase(),
),
};
}
let name = segments.pop().unwrap_or_default().to_ascii_lowercase();
let namespace = segments.pop().unwrap_or_default().to_ascii_lowercase();
(purl_type, namespace, name)
}
/// Typed unsupported failure carried through [`anyhow::Error`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DistroUnsupported {
pub reason: UnsupportedReason,
}
impl std::fmt::Display for DistroUnsupported {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"unsupported distro source request: {:?}",
self.reason
)
}
}
impl std::error::Error for DistroUnsupported {}
fn unsupported(reason: UnsupportedReason) -> anyhow::Error {
anyhow::Error::new(DistroUnsupported { reason })
}
/// Recover the typed reason from an error returned by this source.
pub fn unsupported_reason(error: &anyhow::Error) -> Option<UnsupportedReason> {
error
.downcast_ref::<DistroUnsupported>()
.map(|error| error.reason.clone())
}
/// OCI registry response, including the digest header the shared transport
/// does not expose.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManifestResponse {
pub status: u16,
pub digest: Option<String>,
pub body: Value,
}
/// Header-aware manifest transport. Production sends the OCI index `Accept`
/// value; tests inject a fake.
#[async_trait]
pub trait ManifestHttp: Send + Sync {
async fn fetch_manifest(&self, url: &str, accept: &str) -> Result<ManifestResponse>;
}
pub struct ReqwestManifestHttp {
client: reqwest::Client,
}
impl ReqwestManifestHttp {
pub fn new() -> Result<Self> {
let client = reqwest::Client::builder()
.timeout(HTTP_TIMEOUT)
.user_agent(USER_AGENT)
.redirect(reqwest::redirect::Policy::limited(10))
.build()
.context("build manifest HTTP client")?;
Ok(Self { client })
}
}
#[async_trait]
impl ManifestHttp for ReqwestManifestHttp {
async fn fetch_manifest(&self, url: &str, accept: &str) -> Result<ManifestResponse> {
let response = self
.client
.get(url)
.header(reqwest::header::ACCEPT, accept)
.send()
.await
.with_context(|| format!("fetch OCI manifest {url}"))?;
let status = response.status().as_u16();
let digest = response
.headers()
.get("docker-content-digest")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let body = if status == 200 {
response.json::<Value>().await.unwrap_or(Value::Null)
} else {
Value::Null
};
Ok(ManifestResponse {
status,
digest,
body,
})
}
}
/// Distro/OS release source.
pub struct DistroSource {
http: Arc<dyn RegistryHttp>,
manifest_http: Arc<dyn ManifestHttp>,
endoflife_base_url: String,
rhel_lifecycle_url: String,
registry_base_url: String,
reference_date: String,
}
impl DistroSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Result<Self> {
Ok(Self::with_clients(
http,
Arc::new(ReqwestManifestHttp::new()?),
))
}
pub fn with_clients(http: Arc<dyn RegistryHttp>, manifest_http: Arc<dyn ManifestHttp>) -> Self {
Self {
http,
manifest_http,
endoflife_base_url: DEFAULT_ENDOFLIFE_BASE_URL.to_owned(),
rhel_lifecycle_url: DEFAULT_RHEL_LIFECYCLE_URL.to_owned(),
registry_base_url: DEFAULT_REGISTRY_BASE_URL.to_owned(),
reference_date: chrono::Utc::now().format("%Y-%m-%d").to_string(),
}
}
/// Override endpoints (tests and mirrors).
pub fn with_endpoints(
mut self,
endoflife_base_url: impl Into<String>,
rhel_lifecycle_url: impl Into<String>,
registry_base_url: impl Into<String>,
) -> Self {
self.endoflife_base_url = endoflife_base_url.into().trim_end_matches('/').to_owned();
self.rhel_lifecycle_url = rhel_lifecycle_url.into();
self.registry_base_url = registry_base_url.into().trim_end_matches('/').to_owned();
self
}
/// Reference date for EOL comparisons (`YYYY-MM-DD`). Tests pin it.
pub fn with_reference_date(mut self, date: impl Into<String>) -> Self {
self.reference_date = date.into();
self
}
fn resolve(&self, project: &ProjectRef) -> Result<DistroProject> {
let purl_type = project.purl_type.trim().to_ascii_lowercase();
if !is_distro_purl_type(&purl_type) {
return Err(unsupported(UnsupportedReason::UnknownPurlType(purl_type)));
}
resolve_project(project).ok_or_else(|| unsupported(UnsupportedReason::NoVersions))
}
async fn lifecycle(&self, distro: DistroProject) -> (Vec<LifecycleEntry>, bool) {
let mut entries = BTreeMap::new();
let mut retired = false;
if distro.rhel {
for channel in RHEL_CURATED_CHANNELS {
push_entry(
&mut entries,
LifecycleEntry {
channel: distro_channel(channel.major, channel.edition, None),
version: None,
eol: channel.eol.map(str::to_owned),
},
);
}
if let Ok(Some((plc_entries, is_retired))) = self.redhat_lifecycle().await {
retired = is_retired;
for entry in plc_entries {
push_entry(&mut entries, entry);
}
}
}
if let Some(hint) = distro.product_slug {
// ponytail: the all-products list is fetched per lifecycle call;
// cache the slug map if ingestion starts calling this in a loop.
let slug = self.endoflife_slug(hint).await;
if let Ok(releases) = self.endoflife_releases(&slug).await {
for entry in releases {
push_entry(&mut entries, entry);
}
}
}
// Every lifecycle version implies its channel (`X.Y` also yields `X`,
// or the curated dotless Ubuntu channel). Statuses and versions both
// read this merged view.
let channels: Vec<(String, Option<String>)> = entries
.values()
.map(|entry| (entry.channel.clone(), entry.eol.clone()))
.collect();
for (channel, eol) in channels {
push_entry(
&mut entries,
LifecycleEntry {
channel,
version: None,
eol,
},
);
}
(entries.into_values().collect(), retired)
}
async fn redhat_lifecycle(&self) -> Result<Option<(Vec<LifecycleEntry>, bool)>> {
let payload = self.http.get_json(&self.rhel_lifecycle_url).await?;
let envelope: PlcEnvelope =
serde_json::from_value(payload).context("decode Red Hat lifecycle response")?;
let product = envelope.data.into_iter().find(|product| {
normalize_name(&product.name) == "red hat enterprise linux"
|| product
.former_names
.iter()
.any(|name| normalize_name(name) == "red hat enterprise linux")
});
let Some(product) = product else {
return Ok(None);
};
let mut entries = Vec::new();
for version in &product.versions {
let eol = plc_eol(version);
if let Some(entry) = cycle_entry(&product.slug(), &version.name, eol.clone()) {
entries.push(entry);
}
let mut minors = Vec::new();
for minor in [
version.last_minor_release.as_deref(),
version.final_minor_release.as_deref(),
]
.into_iter()
.flatten()
{
if !minor.is_empty() && !minors.contains(&minor) {
minors.push(minor);
}
}
for minor in minors {
if minor == version.name {
continue;
}
if let Some(entry) = cycle_entry(&product.slug(), minor, eol.clone()) {
entries.push(entry);
}
}
}
Ok(Some((entries, product.is_retired)))
}
async fn endoflife_slug(&self, hint: &str) -> String {
let url = format!("{}/products", self.endoflife_base_url);
let Ok(payload) = self.http.get_json(&url).await else {
return hint.to_owned();
};
let Ok(products) = serde_json::from_value::<EolProducts>(payload) else {
return hint.to_owned();
};
let target = normalize_name(hint);
products
.result
.iter()
.find(|product| {
normalize_name(&product.name) == target
|| product
.aliases
.iter()
.any(|alias| normalize_name(alias) == target)
})
.map(|product| product.name.clone())
.unwrap_or(hint.to_owned())
}
async fn endoflife_releases(&self, slug: &str) -> Result<Vec<LifecycleEntry>> {
let url = format!("{}/products/{}", self.endoflife_base_url, slug);
let payload = self.http.get_json(&url).await?;
let envelope: EolEnvelope =
serde_json::from_value(payload).context("decode endoflife.date response")?;
let releases = if envelope.result.releases.is_empty() {
envelope.result.release_cycles
} else {
envelope.result.releases
};
let mut entries = Vec::new();
for release in releases {
let date = release.eol_from.as_deref().and_then(date_prefix);
let eol: Option<String> = if release.is_eol == Some(true) {
Some(date.unwrap_or_default().to_owned())
} else {
date.map(str::to_owned)
};
if let Some(entry) = cycle_entry(slug, &release.name, eol.clone()) {
entries.push(entry);
}
if let Some(latest) = release.latest
&& !latest.name.is_empty()
&& latest.name != release.name
&& let Some(entry) = cycle_entry(slug, &latest.name, eol)
{
entries.push(entry);
}
}
Ok(entries)
}
fn version_info(&self, entry: LifecycleEntry) -> VersionInfo {
let eol = entry.eol.unwrap_or_default();
let deprecated = !eol.is_empty() && eol <= self.reference_date;
VersionInfo {
raw: entry
.version
.clone()
.unwrap_or_else(|| entry.channel.clone()),
version: entry.version.unwrap_or(entry.channel),
deprecated,
reason: if eol.is_empty() {
String::new()
} else {
format!("eol {eol}")
},
}
}
}
#[async_trait]
impl ReleaseSource for DistroSource {
fn name(&self) -> &'static str {
"distro"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: true,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
let distro = self.resolve(project)?;
let (entries, _) = self.lifecycle(distro).await;
if entries.is_empty() {
return Err(unsupported(UnsupportedReason::NoVersions));
}
let mut versions: Vec<VersionInfo> = entries
.into_iter()
.map(|entry| self.version_info(entry))
.collect();
versions.sort_by(|left, right| {
compare_channel_text(&left.version, &right.version)
.then_with(|| left.version.cmp(&right.version))
});
Ok(versions)
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let distro = self.resolve(project)?;
if !distro.rhel {
return Err(unsupported(UnsupportedReason::NoArtifacts));
}
let (major, stream, arch) = ubi_target(&version.version)?;
let url = format!(
"{}/v2/ubi{major}/ubi/manifests/{stream}",
self.registry_base_url
);
let response = self
.manifest_http
.fetch_manifest(&url, OCI_INDEX_ACCEPT)
.await?;
match response.status {
200 => {}
401 | 403 => {
return Err(unsupported(UnsupportedReason::Unavailable(
"redhat registry requires authentication",
)));
}
_ => return Err(unsupported(UnsupportedReason::NoArtifacts)),
}
let digest = match arch.as_deref() {
Some(arch) => select_manifest(&response.body, Some(arch))
.or_else(|| valid_digest(response.digest.as_deref())),
None => valid_digest(response.digest.as_deref())
.or_else(|| select_manifest(&response.body, None)),
};
let Some(digest) = digest else {
return Err(unsupported(UnsupportedReason::NoArtifacts));
};
let sha256 = digest.strip_prefix("sha256:").unwrap_or(&digest).to_owned();
if !is_sha256_hex(&sha256) {
return Err(unsupported(UnsupportedReason::NoArtifacts));
}
Ok(vec![ArtifactInfo {
file_name: format!("ubi{major}-ubi-{stream}.oci.json"),
url: format!(
"{}/v2/ubi{major}/ubi/manifests/{digest}",
self.registry_base_url
),
sha256: Some(sha256),
size: manifest_size(&response.body, &digest),
mime_type: Some(
response
.body
.get("mediaType")
.and_then(Value::as_str)
.unwrap_or(OCI_INDEX_ACCEPT)
.to_owned(),
),
}])
}
async fn statuses(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
let distro = self.resolve(project)?;
let (entries, retired) = self.lifecycle(distro).await;
if retired {
return Ok(vec![StatusInfo {
status: "archived".to_owned(),
kind: Some("eol".to_owned()),
reason: "product retired".to_owned(),
}]);
}
let target = version.version.trim();
let Some(entry) = entries
.iter()
.find(|entry| entry_matches(entry, target, distro.product))
else {
return Ok(Vec::new());
};
let Some(eol) = entry.eol.as_deref() else {
return Ok(Vec::new());
};
let passed = eol.is_empty() || eol <= self.reference_date.as_str();
if !passed {
return Ok(Vec::new());
}
Ok(vec![StatusInfo {
status: "deprecated".to_owned(),
kind: Some("eol".to_owned()),
reason: if eol.is_empty() {
"eol".to_owned()
} else {
format!("eol {eol}")
},
}])
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let distro = self.resolve(project)?;
Ok(json!({
"source": "distro",
"vendor": distro.vendor,
"product": distro.product,
"project": distro.project,
"purlType": project.purl_type.trim().to_ascii_lowercase(),
"lifecycle": distro.lifecycle_url,
"target": {"os": "linux"},
}))
}
}
#[derive(Debug, Deserialize)]
struct PlcEnvelope {
#[serde(default)]
data: Vec<PlcProduct>,
}
#[derive(Debug, Deserialize)]
struct PlcProduct {
#[serde(default)]
name: String,
#[serde(default)]
former_names: Vec<String>,
#[serde(default)]
is_retired: bool,
#[serde(default)]
versions: Vec<PlcVersion>,
}
impl PlcProduct {
fn slug(&self) -> String {
normalize_name(&self.name).replace(' ', "-")
}
}
#[derive(Debug, Deserialize)]
struct PlcVersion {
#[serde(default)]
name: String,
#[serde(default, rename = "type")]
kind: String,
#[serde(default)]
final_minor_release: Option<String>,
#[serde(default)]
last_minor_release: Option<String>,
#[serde(default)]
phases: Vec<PlcPhase>,
}
#[derive(Debug, Deserialize)]
struct PlcPhase {
#[serde(default)]
name: String,
#[serde(default)]
end_date: Option<String>,
}
fn plc_eol(version: &PlcVersion) -> Option<String> {
let phase_date = |wanted: &str| {
version
.phases
.iter()
.find(|phase| phase.name.eq_ignore_ascii_case(wanted))
.and_then(|phase| phase.end_date.as_deref())
.and_then(date_prefix)
};
if let Some(date) = phase_date("Maintenance support") {
return Some(date.to_owned());
}
if let Some(date) = phase_date("End of Life") {
return Some(date.to_owned());
}
if version.kind.to_ascii_lowercase().contains("end of life") {
return Some(String::new());
}
let mut dates: Vec<&str> = version
.phases
.iter()
.filter(|phase| !phase.name.eq_ignore_ascii_case("general availability"))
.filter_map(|phase| phase.end_date.as_deref())
.filter_map(date_prefix)
.collect();
dates.sort_unstable();
dates.last().map(|date| (*date).to_owned())
}
#[derive(Debug, Default, Deserialize)]
struct EolEnvelope {
#[serde(default)]
result: EolProduct,
}
#[derive(Debug, Default, Deserialize)]
struct EolProduct {
#[serde(default)]
releases: Vec<EolRelease>,
#[serde(default, rename = "releaseCycles")]
release_cycles: Vec<EolRelease>,
}
#[derive(Debug, Default, Deserialize)]
struct EolRelease {
#[serde(default)]
name: String,
#[serde(default, rename = "isEol")]
is_eol: Option<bool>,
#[serde(default, rename = "eolFrom")]
eol_from: Option<String>,
#[serde(default)]
latest: Option<EolLatest>,
}
#[derive(Debug, Default, Deserialize)]
struct EolLatest {
#[serde(default)]
name: String,
}
#[derive(Debug, Default, Deserialize)]
struct EolProducts {
#[serde(default)]
result: Vec<EolProductSummary>,
}
#[derive(Debug, Default, Deserialize)]
struct EolProductSummary {
#[serde(default)]
name: String,
#[serde(default)]
aliases: Vec<String>,
}
fn normalize_name(raw: &str) -> String {
raw.trim()
.to_ascii_lowercase()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn date_prefix(raw: &str) -> Option<&str> {
let date = raw.get(..10)?;
let valid = date.bytes().enumerate().all(|(index, byte)| match index {
4 | 7 => byte == b'-',
_ => byte.is_ascii_digit(),
});
valid.then_some(date)
}
/// Split a lifecycle cycle name into channel and version. `X.Y` is a version
/// under channel `X`; Ubuntu point releases are their own dotless channel
/// (`20.04` -> `20-04`) because the channel grammar forbids dots.
fn cycle_entry(slug: &str, name: &str, eol: Option<String>) -> Option<LifecycleEntry> {
let name = name.trim();
if name.is_empty() {
return None;
}
if name.contains('.') {
let channel = if slug == "ubuntu" {
ubuntu_channel(name)
} else {
name.split('.').next().unwrap_or(name).to_owned()
};
return Some(LifecycleEntry {
channel,
version: Some(name.to_owned()),
eol,
});
}
Some(LifecycleEntry {
channel: distro_channel(name, None, None),
version: None,
eol,
})
}
fn push_entry(
entries: &mut BTreeMap<(String, Option<String>), LifecycleEntry>,
entry: LifecycleEntry,
) {
match entries.entry((entry.channel.clone(), entry.version.clone())) {
std::collections::btree_map::Entry::Occupied(mut occupied) => {
let has_date = entry.eol.as_deref().is_some_and(|eol| !eol.is_empty());
if has_date || occupied.get().eol.is_none() {
occupied.get_mut().eol = entry.eol;
}
}
std::collections::btree_map::Entry::Vacant(vacant) => {
vacant.insert(entry);
}
}
}
fn entry_matches(entry: &LifecycleEntry, target: &str, product: &str) -> bool {
if entry.version.as_deref() == Some(target) || entry.channel == target {
return true;
}
if let Some((major, _)) = target.split_once('.') {
return if product == "Ubuntu" {
entry.channel == ubuntu_channel(target)
} else {
entry.channel == major
};
}
false
}
/// Ubuntu point releases name their own dotless channel (`20.04` -> `20-04`);
/// patch releases belong to the matching minor channel.
fn ubuntu_channel(name: &str) -> String {
let mut parts = name.split('.');
let major = parts.next().unwrap_or(name);
match parts.next() {
Some(minor) => distro_channel(&format!("{major}.{minor}"), None, None),
None => major.to_owned(),
}
}
/// Numeric-aware ordering for channel and version text (`9` < `10`).
fn compare_channel_text(left: &str, right: &str) -> Ordering {
let mut left_parts = left.split('.');
let mut right_parts = right.split('.');
loop {
match (left_parts.next(), right_parts.next()) {
(None, None) => return Ordering::Equal,
(None, Some(_)) => return Ordering::Less,
(Some(_), None) => return Ordering::Greater,
(Some(left), Some(right)) => {
let ordering = match (left.parse::<u64>(), right.parse::<u64>()) {
(Ok(left), Ok(right)) => left.cmp(&right),
_ => left.cmp(right),
};
if ordering != Ordering::Equal {
return ordering;
}
}
}
}
}
fn ubi_target(version: &str) -> Result<(String, String, Option<String>)> {
let raw = version.trim();
if raw.is_empty() {
return Err(unsupported(UnsupportedReason::NoArtifacts));
}
let tokens: Vec<&str> = raw.split('-').filter(|token| !token.is_empty()).collect();
let Some(first) = tokens.first() else {
return Err(unsupported(UnsupportedReason::NoArtifacts));
};
let major = first.split('.').next().unwrap_or(first);
if major.is_empty() || major.len() > 2 || !major.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(unsupported(UnsupportedReason::NoArtifacts));
}
let arch = tokens
.iter()
.skip(1)
.find(|token| RHEL_ARCHES.contains(token))
.map(|token| (*token).to_owned());
let stream = if raw
.strip_prefix(major)
.is_some_and(|rest| rest.starts_with('.'))
{
let end = raw.find('-').unwrap_or(raw.len());
&raw[..end]
} else {
major
};
let valid = !stream.is_empty()
&& stream
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
if !valid {
return Err(unsupported(UnsupportedReason::NoArtifacts));
}
Ok((major.to_owned(), stream.to_owned(), arch))
}
fn valid_digest(digest: Option<&str>) -> Option<String> {
let digest = digest?.trim();
let hex = digest.strip_prefix("sha256:")?;
is_sha256_hex(hex).then(|| digest.to_owned())
}
fn is_sha256_hex(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}
fn select_manifest(body: &Value, arch: Option<&str>) -> Option<String> {
let manifests = body.get("manifests")?.as_array()?;
let wanted = match arch {
Some("aarch64") => "arm64",
Some("x86_64") | None => "amd64",
Some(arch) => arch,
};
let matching = manifests.iter().find(|manifest| {
manifest
.get("platform")
.and_then(|platform| platform.get("architecture"))
.and_then(Value::as_str)
.is_some_and(|value| value == wanted || (wanted == "amd64" && value == "x86_64"))
&& manifest
.get("platform")
.and_then(|platform| platform.get("os"))
.and_then(Value::as_str)
.is_none_or(|os| os == "linux")
});
let manifest = matching.or_else(|| manifests.first());
valid_digest(
manifest
.and_then(|manifest| manifest.get("digest"))
.and_then(Value::as_str),
)
}
fn manifest_size(body: &Value, digest: &str) -> Option<u64> {
body.get("manifests")?
.as_array()?
.iter()
.find(|manifest| manifest.get("digest").and_then(Value::as_str) == Some(digest))
.and_then(|manifest| manifest.get("size"))
.and_then(Value::as_u64)
}