1use std::sync::OnceLock;
6
7use adk_awp::signing::keys::{Dated, delegated_key, verify_key_set};
8use async_trait::async_trait;
9use awp_types::{KeyScope, KeySet, PublicKeyJwk};
10use regex::Regex;
11use scraper::{Html, Selector};
12use url::Url;
13
14use super::{CheckResult, CheckStatus, Finding, GateCheck, GateExtension, GateInput, GateMode};
15use crate::error::Result;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ThirdPartyResources {
36 origin: Option<String>,
37}
38
39const LOADS: &[(&str, &str)] = &[
41 ("script[src]", "src"),
42 ("iframe[src]", "src"),
43 ("frame[src]", "src"),
44 ("img[src]", "src"),
45 ("img[srcset]", "srcset"),
46 ("source[src]", "src"),
47 ("source[srcset]", "srcset"),
48 ("video[src]", "src"),
49 ("video[poster]", "poster"),
50 ("audio[src]", "src"),
51 ("track[src]", "src"),
52 ("embed[src]", "src"),
53 ("object[data]", "data"),
54 ("input[type=image][src]", "src"),
55 ("link[rel~=stylesheet][href]", "href"),
56 ("link[rel~=preload][href]", "href"),
57 ("link[rel~=modulepreload][href]", "href"),
58 ("link[rel~=prefetch][href]", "href"),
59 ("link[rel~=icon][href]", "href"),
60 ("link[rel~=manifest][href]", "href"),
61];
62
63fn css_urls(css: &str) -> Vec<String> {
65 static PATTERN: OnceLock<Regex> = OnceLock::new();
66 let pattern = PATTERN.get_or_init(|| {
67 Regex::new(r#"(?i)url\(\s*['"]?([^'")\s]+)['"]?\s*\)|@import\s+['"]([^'"]+)['"]"#)
68 .expect("a static regex")
69 });
70 pattern
71 .captures_iter(css)
72 .filter_map(|c| c.get(1).or_else(|| c.get(2)).map(|m| m.as_str().to_string()))
73 .collect()
74}
75
76impl ThirdPartyResources {
77 pub fn new(origin: &str) -> Self {
79 Self { origin: Url::parse(origin).ok().map(|url| url.origin().ascii_serialization()) }
80 }
81
82 pub fn third_party(&self, reference: &str) -> bool {
84 let reference = reference.trim();
85 if reference.starts_with("//") {
86 return true;
87 }
88 match Url::parse(reference) {
89 Ok(url) if matches!(url.scheme(), "http" | "https") => {
90 self.origin.as_deref() != Some(url.origin().ascii_serialization().as_str())
91 }
92 Ok(_) | Err(_) => false,
93 }
94 }
95
96 fn finding(&self, path: &str, what: &str, value: &str) -> Finding {
97 Finding::blocking(
98 "third-party-resource",
99 Some(path.to_string()),
100 None,
101 format!(
102 "{what} loads {value} from another origin; the site ships no third-party scripts \
103 or trackers (spec 3.5 §7.16.1)"
104 ),
105 )
106 }
107}
108
109#[async_trait]
110impl GateExtension for ThirdPartyResources {
111 fn check(&self) -> GateCheck {
112 GateCheck::ThirdPartyResources
113 }
114
115 fn runs_in(&self, _mode: GateMode) -> bool {
116 true
117 }
118
119 async fn run(&self, input: &GateInput<'_>) -> Result<CheckResult> {
120 let paths = match input.changed {
121 Some(_) => &input.report.written,
122 None => &input.report.outputs,
123 };
124 let mut findings = Vec::new();
125 for path in paths {
126 let full = input.out.join(path.trim_start_matches('/'));
127 if path.ends_with(".css") {
128 let Ok(css) = tokio::fs::read_to_string(&full).await else { continue };
129 for value in css_urls(&css).iter().filter(|v| self.third_party(v)) {
130 findings.push(self.finding(path, "the stylesheet", value));
131 }
132 continue;
133 }
134 if !(path.ends_with(".html") || path.ends_with(".htm")) {
135 continue;
136 }
137 let Ok(text) = tokio::fs::read_to_string(&full).await else { continue };
138 let document = Html::parse_document(&text);
139 for (selector, attribute) in LOADS {
140 let selector = Selector::parse(selector).expect("a static selector");
141 for element in document.select(&selector) {
142 let value = element.attr(attribute).unwrap_or_default();
143 let references: Vec<&str> = if attribute.ends_with("srcset") {
144 value
145 .split(',')
146 .filter_map(|candidate| candidate.split_whitespace().next())
147 .collect()
148 } else {
149 vec![value]
150 };
151 for reference in references.into_iter().filter(|r| self.third_party(r)) {
152 let what = format!("<{}>", element.value().name());
153 findings.push(self.finding(path, &what, reference));
154 }
155 }
156 }
157 let styles = Selector::parse("style, [style]").expect("a static selector");
158 for element in document.select(&styles) {
159 let css = if element.value().name() == "style" {
160 element.text().collect::<String>()
161 } else {
162 element.attr("style").unwrap_or_default().to_string()
163 };
164 for value in css_urls(&css).iter().filter(|v| self.third_party(v)) {
165 findings.push(self.finding(path, "an inline style", value));
166 }
167 }
168 }
169 let status = if findings.is_empty() { CheckStatus::Passed } else { CheckStatus::Failed };
170 Ok(CheckResult {
171 check: GateCheck::ThirdPartyResources,
172 status,
173 findings,
174 note: Some("no third-party scripts, trackers or other resources".into()),
175 })
176 }
177}
178
179const KEYS: &str = ".well-known/awp/keys.json";
181
182#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct ReleaseDelegation {
201 kid: String,
202 key: PublicKeyJwk,
203 key_file: String,
204}
205
206impl ReleaseDelegation {
207 pub fn new(kid: impl Into<String>, key: PublicKeyJwk, key_file: impl Into<String>) -> Self {
209 Self { kid: kid.into(), key, key_file: key_file.into() }
210 }
211
212 fn problem(&self, keys: Option<&[u8]>) -> Option<String> {
214 let Some(bytes) = keys else {
215 return Some("the site has no AWP key set".to_string());
216 };
217 let keys: KeySet = match serde_json::from_slice(bytes) {
218 Ok(keys) => keys,
219 Err(error) => return Some(format!("its key set is not valid: {error}")),
220 };
221 if let Err(error) = verify_key_set(&keys) {
222 return Some(format!("its key set does not verify: {error}"));
223 }
224 match delegated_key(&keys, &self.kid, KeyScope::Release, Dated::Live(chrono::Utc::now())) {
225 Ok(key) if *key == self.key => None,
226 Ok(_) => Some(format!("the key set's `{}` is not the release key", self.kid)),
227 Err(error) => Some(format!("the release key `{}` is not delegated: {error}", self.kid)),
228 }
229 }
230}
231
232#[async_trait]
233impl GateExtension for ReleaseDelegation {
234 fn check(&self) -> GateCheck {
235 GateCheck::Signing
236 }
237
238 fn runs_in(&self, _mode: GateMode) -> bool {
239 true
240 }
241
242 async fn run(&self, input: &GateInput<'_>) -> Result<CheckResult> {
243 let documents = &input.project.documents;
244 let keys = match documents.get(KEYS).or_else(|| documents.get(&format!("/{KEYS}"))) {
245 Some(bytes) => Some(bytes.to_vec()),
246 None => tokio::fs::read(input.out.join(KEYS)).await.ok(),
247 };
248 let findings: Vec<Finding> = self
249 .problem(keys.as_deref())
250 .map(|problem| Finding {
251 rule: "release-delegation".into(),
252 severity: super::Severity::Critical,
253 blocking: true,
254 path: Some(format!("/{KEYS}")),
255 item: None,
256 message: format!(
257 "{problem}. The owner signs at a terminal: `adk-rust awp keys rotate` makes \
258 the root and the key set, then `adk-rust awp keys delegate --scope release \
259 --key {}` delegates the release key (spec 3.5 D-11)",
260 self.key_file
261 ),
262 })
263 .into_iter()
264 .collect();
265 let status = if findings.is_empty() { CheckStatus::Passed } else { CheckStatus::Failed };
266 Ok(CheckResult {
267 check: GateCheck::Signing,
268 status,
269 findings,
270 note: Some("the release key is delegated by the owner's root".into()),
271 })
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278
279 #[test]
280 fn css_references_are_read() {
281 let css = "@import 'https://fonts.example/a.css'; body { background: url(\"/bg.png\") } \
282 h1 { background-image: url( https://t.example/p.gif ) }";
283 assert_eq!(
284 css_urls(css),
285 ["https://fonts.example/a.css", "/bg.png", "https://t.example/p.gif"]
286 );
287 }
288}