ping-rust 0.2.2

Menu-driven installer and manager for the shoes proxy server
use super::*;
use time::{Date, Duration, Month, OffsetDateTime, Time};

// Read only the two validity values in certificates generated by this fixture.
// Production code uses generation metadata, not an X.509 parser.
fn tlv<'a>(input: &mut &'a [u8]) -> (u8, &'a [u8]) {
    let tag = input[0];
    let mut length = input[1] as usize;
    let mut header = 2;
    if length & 0x80 != 0 {
        let count = length & 0x7f;
        length = input[2..2 + count]
            .iter()
            .fold(0, |n, b| (n << 8) | *b as usize);
        header += count;
    }
    let value = &input[header..header + length];
    *input = &input[header + length..];
    (tag, value)
}

fn certificate_dates(path: &Path) -> (OffsetDateTime, OffsetDateTime) {
    let pem = fs::read_to_string(path).unwrap();
    let der = STANDARD
        .decode(
            pem.lines()
                .filter(|l| !l.starts_with("---"))
                .collect::<String>(),
        )
        .unwrap();
    let mut certificate = tlv(&mut der.as_slice()).1;
    let mut tbs = tlv(&mut certificate).1;
    for _ in 0..4 {
        tlv(&mut tbs);
    } // version, serial, signature, issuer
    let mut validity = tlv(&mut tbs).1;
    let parse = |(tag, value): (u8, &[u8])| {
        let text = std::str::from_utf8(value).unwrap();
        let (year, start) = if tag == 0x17 {
            let year: i32 = text[..2].parse().unwrap();
            (if year >= 50 { 1900 + year } else { 2000 + year }, 2)
        } else {
            assert_eq!(tag, 0x18);
            (text[..4].parse().unwrap(), 4)
        };
        let n = |offset: usize| {
            text[start + offset..start + offset + 2]
                .parse::<u8>()
                .unwrap()
        };
        Date::from_calendar_date(year, Month::try_from(n(0)).unwrap(), n(2))
            .unwrap()
            .with_time(Time::from_hms(n(4), n(6), n(8)).unwrap())
            .assume_utc()
    };
    (parse(tlv(&mut validity)), parse(tlv(&mut validity)))
}

#[tokio::test]
async fn naive_test_certificate_actual_der_has_bounded_validity_and_metadata() {
    let dir = tempfile::tempdir().unwrap();
    let mut request = super::tests::request(Protocol::NaiveProxy, dir.path().join("naive.yaml"));
    request.options.naive_self_signed = true;
    let started = OffsetDateTime::now_utc();
    let result = generate_inner(request, false).await.unwrap();
    let (before, after) = certificate_dates(result.certificate_path.as_ref().unwrap());
    assert!(before <= started, "certificate must already be valid");
    assert!(
        before >= started - Duration::hours(1) - Duration::seconds(2),
        "not_before must tolerate one hour of skew"
    );
    assert!(
        after - before <= Duration::days(397),
        "Chromium rejects excessively long validity"
    );
    let issue_date = before.date();
    let expected_days = if issue_date >= Date::from_calendar_date(2029, Month::March, 15).unwrap() {
        46
    } else if issue_date >= Date::from_calendar_date(2027, Month::March, 15).unwrap() {
        99
    } else if issue_date >= Date::from_calendar_date(2026, Month::March, 15).unwrap() {
        199
    } else {
        397
    };
    assert_eq!(after - before, Duration::days(expected_days));
    let profile = serde_json::to_value(&result.profile).unwrap();
    assert_eq!(
        profile["naive_certificate_validity"]["not_before"],
        before.unix_timestamp()
    );
    assert_eq!(
        profile["naive_certificate_validity"]["not_after"],
        after.unix_timestamp()
    );
}

#[tokio::test]
async fn other_protocol_self_signed_validity_is_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let result = generate_inner(
        super::tests::request(Protocol::Hysteria2, dir.path().join("hy.yaml")),
        false,
    )
    .await
    .unwrap();
    let (before, after) = certificate_dates(result.certificate_path.as_ref().unwrap());
    assert_eq!(before.year(), 1975);
    assert_eq!(after.year(), 4096);
    assert!(serde_json::to_value(result.profile)
        .unwrap()
        .get("naive_certificate_validity")
        .is_none());
}

#[tokio::test]
async fn naive_legacy_expiring_and_external_profiles_are_distinguished() {
    let dir = tempfile::tempdir().unwrap();
    let mut request = super::tests::request(Protocol::NaiveProxy, dir.path().join("naive.yaml"));
    request.options.naive_self_signed = true;
    let result = generate_inner(request, false).await.unwrap();
    let mut json = serde_json::to_value(&result.profile).unwrap();
    json.as_object_mut()
        .unwrap()
        .remove("naive_certificate_validity");
    let mut legacy: ManagedProfile = serde_json::from_value(json).unwrap();
    let now = Date::from_calendar_date(2026, Month::October, 1)
        .unwrap()
        .midnight()
        .assume_utc()
        .unix_timestamp();
    assert!(legacy
        .naive_certificate_warning(now)
        .unwrap()
        .contains("旧证书"));
    legacy.self_signed_certificate = false;
    assert!(legacy.naive_certificate_warning(now).is_none());
    legacy.self_signed_certificate = true;
    for (remaining, expected) in [
        (199 * 86400 / 3 - 1, "不足有效期的 1/3"),
        (0, "已过期"),
        (-1, "已过期"),
    ] {
        legacy.naive_certificate_validity = Some(NaiveCertificateValidity {
            not_before: now + remaining - 199 * 86400,
            not_after: now + remaining,
        });
        assert!(legacy
            .naive_certificate_warning(now)
            .unwrap()
            .contains(expected));
    }
    legacy.naive_certificate_validity = Some(NaiveCertificateValidity {
        not_before: now + 199 * 86400 / 3 - 199 * 86400,
        not_after: now + 199 * 86400 / 3,
    });
    assert!(legacy.naive_certificate_warning(now).is_none());
    legacy.naive_certificate_validity = Some(NaiveCertificateValidity {
        not_before: now - 3600,
        not_after: now - 3600 + 397 * 86400,
    });
    assert!(legacy
        .naive_certificate_warning(now)
        .unwrap()
        .contains("超过"));
    legacy
        .naive_certificate_validity
        .as_mut()
        .unwrap()
        .not_after = now - 3600 + 199 * 86400;
    assert!(legacy.naive_certificate_warning(now).is_none());
}

#[test]
fn naive_sc081_phase_boundaries_use_injected_not_before_in_actual_certificate() {
    let root = tempfile::tempdir().unwrap();
    for (year, before_days, after_days) in [(2026, 397, 199), (2027, 199, 99), (2029, 99, 46)] {
        let boundary = Date::from_calendar_date(year, Month::March, 15)
            .unwrap()
            .midnight()
            .assume_utc();
        for (offset, days) in [(-1, before_days), (0, after_days), (1, after_days)] {
            let not_before = boundary + Duration::seconds(offset);
            let now = not_before + Duration::hours(1);
            let certificate = root.path().join("certificate.pem");
            let key = root.path().join("key.pem");
            let validity = naive_certificate::write_test_certificate_at(
                "acceptance.example.invalid",
                &certificate,
                &key,
                now,
            )
            .unwrap();
            let (actual_before, actual_after) = certificate_dates(&certificate);
            assert_eq!(actual_before, not_before);
            assert_eq!(
                actual_after - actual_before,
                Duration::days(days),
                "phase boundary: {year}, offset={offset}"
            );
            assert_eq!(validity.not_before, actual_before.unix_timestamp());
            assert_eq!(validity.not_after, actual_after.unix_timestamp());
        }
    }
}

#[test]
fn naive_warning_scales_for_each_phase_and_respects_original_issue_phase() {
    let mut profile = ManagedProfile {
        id: Uuid::nil(),
        name: "test-naive".to_owned(),
        port: 443,
        server_address: None,
        credentials: Credentials::NaiveProxy {
            username: String::new(),
            password: String::new(),
            server_name: "acceptance.example.invalid".to_owned(),
            padding: true,
            udp_enabled: false,
            fallback: None,
        },
        certificate_path: None,
        certificate_key_path: None,
        self_signed_certificate: true,
        naive_certificate_validity: None,
        h2mux: Default::default(),
    };
    for (year, days) in [(2026, 199), (2027, 99), (2029, 46)] {
        let start = Date::from_calendar_date(year, Month::March, 15)
            .unwrap()
            .midnight()
            .assume_utc()
            .unix_timestamp();
        let duration = days * 86400;
        let end = start + duration;
        profile.naive_certificate_validity = Some(NaiveCertificateValidity {
            not_before: start,
            not_after: end,
        });
        let whole_threshold = duration / 3;
        // Strict inequality at the exact 1/3 point; round fractional-second thresholds upward.
        let rounded_threshold = (duration + 2) / 3;
        assert!(profile
            .naive_certificate_warning(end - rounded_threshold)
            .is_none());
        assert!(profile
            .naive_certificate_warning(end - whole_threshold + 1)
            .unwrap()
            .contains("不足有效期的 1/3"));
    }
    let start = Date::from_calendar_date(2026, Month::March, 14)
        .unwrap()
        .midnight()
        .assume_utc()
        .unix_timestamp();
    profile.naive_certificate_validity = Some(NaiveCertificateValidity {
        not_before: start,
        not_after: start + 397 * 86400,
    });
    assert!(
        profile
            .naive_certificate_warning(start + 2 * 86400)
            .is_none(),
        "later policy must not reclassify a compliant earlier-issued certificate"
    );
}

#[tokio::test]
async fn naive_regeneration_rollback_restores_original_profile_and_certificate() {
    let dir = tempfile::tempdir().unwrap();
    let config = dir.path().join("config.yaml");
    let state_path = dir.path().join("state.json");
    let profiles = dir.path().join("profiles");
    let mut request = super::tests::request(Protocol::NaiveProxy, dir.path().join("initial.yaml"));
    request.options.naive_self_signed = true;
    let generated = generate_inner(request, false).await.unwrap();
    let mut profile = generated.profile;
    let mut servers = load_servers(&generated.config_path).unwrap();
    // Reproduce an old profile without expiry metadata.
    profile.naive_certificate_validity = None;
    let old_certificate = profile.certificate_path.clone().unwrap();
    let old_key = profile.certificate_key_path.clone().unwrap();
    let old_pem = fs::read(&old_certificate).unwrap();
    let state = ManagedState {
        profiles: vec![profile.clone()],
        ..Default::default()
    };
    commit_managed_with_state_writer(
        &config,
        &state_path,
        &profiles,
        &servers,
        &state,
        save_state_to,
    )
    .unwrap();
    let original_config = fs::read(&config).unwrap();
    let original_state = fs::read(&state_path).unwrap();
    let mut rollback = ManagedRollback {
        config: Some(original_config.clone()),
        state: Some(original_state.clone()),
        profiles: ProfileDirectorySnapshot::capture(&profiles).unwrap(),
        generated_certificate: None,
        generated_certificate_key: None,
    };
    let mut cleanup =
        regenerate_naive_test_certificate(&mut servers[0], &mut profile, dir.path(), &mut rollback)
            .unwrap();
    let new_certificate = profile.certificate_path.clone().unwrap();
    let new_key = profile.certificate_key_path.clone().unwrap();
    assert_ne!(old_certificate, new_certificate);
    assert!(profile.naive_certificate_validity.is_some());
    let updated = ManagedState {
        profiles: vec![profile],
        ..Default::default()
    };
    commit_managed_with_state_writer(
        &config,
        &state_path,
        &profiles,
        &servers,
        &updated,
        save_state_to,
    )
    .unwrap();
    cleanup.disarm();
    // The deployment activation-failure path invokes this same snapshot restore.
    rollback
        .restore_to(&config, &state_path, &profiles)
        .unwrap();
    assert_eq!(fs::read(config).unwrap(), original_config);
    assert_eq!(fs::read(state_path).unwrap(), original_state);
    assert_eq!(fs::read(old_certificate).unwrap(), old_pem);
    assert!(old_key.exists());
    assert!(!new_certificate.exists());
    assert!(!new_key.exists());
}