From d8f69d99c53d0174cfe9b9aa05b5e9bf2ebbaa92 Mon Sep 17 00:00:00 2001 From: Antony Date: Tue, 24 Nov 2026 19:50:14 +0530 Subject: [PATCH 1/6] test: preflight cases for Azure, GitLab, npm, Hugging Face and PyPI credentials --- src/preflight.rs | 29 +++++++++++++++++++++++++++++ tests/local_patch.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..b003373 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -344,6 +344,23 @@ mod tests { '8', "a Proofline token", ), + ( + &["AccountKey=", "accountkey="][..], + 86, + "Az09+/", + '!', + "an Azure Storage account key", + ), + ( + &["glpat-"][..], + 20, + "Az09_-", + '.', + "a GitLab personal access token", + ), + (&["npm_"][..], 36, "Az09", '_', "an npm access token"), + (&["pypi-"][..], 85, "Az09_-", '.', "a PyPI API token"), + (&["hf_"][..], 34, "Az09", '_', "a Hugging Face access token"), ]; for (prefixes, minimum, alphabet, invalid, label) in cases { let body: String = alphabet.chars().cycle().take(minimum).collect(); @@ -381,6 +398,18 @@ mod tests { assert_eq!(secret_shape("-----BEGIN CERTIFICATE-----"), None); } + #[test] + fn identifiers_and_placeholders_near_credential_prefixes_have_no_secret_shape() { + for text in [ + "npm_config_registry", + "self.hf_model", + "AccountKey=", + "AccountKey=${STORAGE_KEY}", + ] { + assert_eq!(secret_shape(text), None, "{text}"); + } + } + #[test] fn ordinary_text_has_no_secret_shape() { assert_eq!( diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 6da45f8..131a327 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -554,6 +554,36 @@ async fn local_selection_uploads_only_selected_bytes_and_refuses_before_http() { server.close().await; } +#[tokio::test] +async fn an_azure_storage_connection_string_refuses_before_http() { + let key = format!( + "{}==", + "Az09+/".chars().cycle().take(86).collect::() + ); + // A tracked file, so the default selection includes the change, and not a + // .env path, so only the credential shape can refuse it. + let checkout = Checkout::new(&[("appsettings.json", "{\n}\n")]).await; + checkout + .write( + "appsettings.json", + &format!( + "{{\n \"Storage\": \"DefaultEndpointsProtocol=https;AccountName=acme;AccountKey={key};EndpointSuffix=core.windows.net\"\n}}\n" + ), + ) + .await; + let index = checkout.index().await; + let server = Server::start(true).await; + let output = checkout.review(&server, &[], &[]).await; + assert_refusal( + &output, + "an Azure Storage account key at \"appsettings.json\":2 (new line)", + &key, + ); + server.assert_no_requests(); + assert_eq!(checkout.index().await, index); + server.close().await; +} + #[tokio::test] async fn added_context_deleted_and_quoted_content_refuses_before_http() { let github = format!("ghp_{}", "A".repeat(36)); From ebb06855ae0358097d290f565ce6e51ee0214bd3 Mon Sep 17 00:00:00 2001 From: Antony Date: Tue, 24 Nov 2026 20:23:22 +0530 Subject: [PATCH 2/6] feat(preflight): detect Azure Storage, GitLab, npm, Hugging Face and PyPI credentials --- src/preflight.rs | 140 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 138 insertions(+), 2 deletions(-) diff --git a/src/preflight.rs b/src/preflight.rs index b003373..569d920 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -1,5 +1,7 @@ //! Local refusals before any patch bytes leave the checkout. +use std::borrow::Cow; + use crate::git::{LocalChanges, PatchPaths}; #[derive(Debug, thiserror::Error)] @@ -185,6 +187,16 @@ fn base32(byte: u8) -> bool { byte.is_ascii_uppercase() || matches!(byte, b'2'..=b'7') } +/// The RFC 4648 base64 alphabet, without `=` padding. +fn base64(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/') +} + +/// The RFC 4648 URL- and filename-safe base64 alphabet, without `=` padding. +fn base64url(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') +} + fn has_token(text: &str, prefixes: &[&str], minimum: usize, body: fn(u8) -> bool) -> bool { prefixes.iter().any(|prefix| { text.match_indices(*prefix).any(|(start, prefix)| { @@ -273,8 +285,88 @@ const TOKEN_SHAPES: &[TokenShape] = &[ minimum: 52, body: base32, }, + // https://learn.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string + // A real key is 88 + // characters including its `==` padding; the rule requires only the 86 + // base64 characters before it and does not check the padding. Connection + // string keywords are case-insensitive, but only these two casings are + // covered, because `has_token` matches prefixes exactly. + TokenShape { + kind: "an Azure Storage account key", + prefixes: &["AccountKey=", "accountkey="], + minimum: 86, + body: base64, + }, + // https://docs.gitlab.com/user/profile/personal_access_tokens/ + // `glpat-` followed by 20 characters. + TokenShape { + kind: "a GitLab personal access token", + prefixes: &["glpat-"], + minimum: 20, + body: base64url, + }, + // https://docs.npmjs.com/about-access-tokens + // `npm_` followed by 36 alphanumerics. + TokenShape { + kind: "an npm access token", + prefixes: &["npm_"], + minimum: 36, + body: alphanumeric, + }, + // https://huggingface.co/docs/hub/security-tokens documents only the `hf_` + // prefix. The length and alphabet are not vendor-documented: a measured + // token had 34 letters after `hf_`, matching the gitleaks rule. + // Alphanumeric keeps the rule a superset of that shape if the format adds + // digits. + TokenShape { + kind: "a Hugging Face access token", + prefixes: &["hf_"], + minimum: 34, + body: alphanumeric, + }, + // https://docs.pypi.org/api/tokens/ + // `pypi-` followed by a base64url body. + TokenShape { + kind: "a PyPI API token", + prefixes: &["pypi-"], + minimum: 85, + body: base64url, + }, ]; +/// Azurite's well-known development account key for `devstoreaccount1`, which +/// Microsoft publishes under "Use a well-known storage account and key" at +/// . +/// It authorizes only the local emulator, so an exact occurrence is no secret. +const AZURITE_ACCOUNT_KEY: &str = + "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; + +/// `text` with each exact occurrence of [`AZURITE_ACCOUNT_KEY`] blanked by as +/// many spaces, so other offsets are unchanged. An occurrence inside a longer +/// key is a different key, so it stays: a base64 byte before it, or a base64 +/// or `=` byte after it, extends the key. A `=` before it ends a keyword such +/// as `AccountKey=`, because padding only ends a key. +fn without_azurite_key(text: &str) -> Cow<'_, str> { + let bytes = text.as_bytes(); + let mut exempt = Cow::Borrowed(text); + for (start, key) in text.match_indices(AZURITE_ACCOUNT_KEY) { + let end = start + key.len(); + let extended_before = start + .checked_sub(1) + .and_then(|index| bytes.get(index)) + .is_some_and(|byte| base64(*byte)); + let extended_after = bytes + .get(end) + .is_some_and(|byte| base64(*byte) || *byte == b'='); + if !extended_before && !extended_after { + exempt + .to_mut() + .replace_range(start..end, &" ".repeat(key.len())); + } + } + exempt +} + /// Literal private-key markers and distinctive credential prefixes. This /// check refuses the original bytes; it never rewrites the reviewed patch. fn secret_shape(text: &str) -> Option<&'static str> { @@ -283,15 +375,16 @@ fn secret_shape(text: &str) -> Option<&'static str> { { return Some("a private-key marker"); } + let text = without_azurite_key(text); TOKEN_SHAPES .iter() - .find(|shape| has_token(text, shape.prefixes, shape.minimum, shape.body)) + .find(|shape| has_token(&text, shape.prefixes, shape.minimum, shape.body)) .map(|shape| shape.kind) } #[cfg(test)] mod tests { - use super::secret_shape; + use super::{AZURITE_ACCOUNT_KEY, secret_shape}; #[test] fn credential_families_refuse_minimum_bodies_but_accept_short_or_invalid_ones() { @@ -405,11 +498,54 @@ mod tests { "self.hf_model", "AccountKey=", "AccountKey=${STORAGE_KEY}", + "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;", ] { assert_eq!(secret_shape(text), None, "{text}"); } } + #[test] + fn the_azurite_exception_covers_only_the_exact_key() { + let azurite = format!( + "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey={AZURITE_ACCOUNT_KEY};BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;" + ); + let github = format!("ghp_{}", "S".repeat(36)); + let real = format!( + "{}==", + "Az09+/".chars().cycle().take(86).collect::() + ); + let azure = Some("an Azure Storage account key"); + for (text, expected, case) in [ + ( + format!("AccountKey=X{AZURITE_ACCOUNT_KEY}"), + azure, + "a base64 byte before the key", + ), + ( + format!("AccountKey={AZURITE_ACCOUNT_KEY}A"), + azure, + "a base64 byte after the padding", + ), + ( + format!("AccountKey={AZURITE_ACCOUNT_KEY}="), + azure, + "a `=` byte after the padding", + ), + ( + format!("{azurite} token={github}"), + Some("a GitHub token"), + "a GitHub token on the same line", + ), + ( + format!("{azurite} AccountName=acme;AccountKey={real};"), + azure, + "a real account key on the same line", + ), + ] { + assert_eq!(secret_shape(&text), expected, "{case}"); + } + } + #[test] fn ordinary_text_has_no_secret_shape() { assert_eq!( From fa3da98e5394a82784152ce5d0dd9a8f8da7a4bb Mon Sep 17 00:00:00 2001 From: Antony Date: Tue, 24 Nov 2026 20:45:08 +0530 Subject: [PATCH 3/6] fix(preflight): scope Azurite exception to the Azure rule; tighten alphabet tests --- src/preflight.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/src/preflight.rs b/src/preflight.rs index 569d920..5de34e1 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -292,7 +292,7 @@ const TOKEN_SHAPES: &[TokenShape] = &[ // string keywords are case-insensitive, but only these two casings are // covered, because `has_token` matches prefixes exactly. TokenShape { - kind: "an Azure Storage account key", + kind: AZURE_ACCOUNT_KEY_KIND, prefixes: &["AccountKey=", "accountkey="], minimum: 86, body: base64, @@ -334,6 +334,9 @@ const TOKEN_SHAPES: &[TokenShape] = &[ }, ]; +/// The kind of the row that the Azurite exception applies to. +const AZURE_ACCOUNT_KEY_KIND: &str = "an Azure Storage account key"; + /// Azurite's well-known development account key for `devstoreaccount1`, which /// Microsoft publishes under "Use a well-known storage account and key" at /// . @@ -375,10 +378,19 @@ fn secret_shape(text: &str) -> Option<&'static str> { { return Some("a private-key marker"); } - let text = without_azurite_key(text); + let exempt = without_azurite_key(text); TOKEN_SHAPES .iter() - .find(|shape| has_token(&text, shape.prefixes, shape.minimum, shape.body)) + .find(|shape| { + // Only an account key can be the Azurite key. Every other family + // reads the original text, so a token that overlaps it still counts. + let text = if shape.kind == AZURE_ACCOUNT_KEY_KIND { + &*exempt + } else { + text + }; + has_token(text, shape.prefixes, shape.minimum, shape.body) + }) .map(|shape| shape.kind) } @@ -451,8 +463,40 @@ mod tests { '.', "a GitLab personal access token", ), + // As for `ghs_`, the other base64 alphabet's punctuation is + // invalid in each base64 family. + ( + &["AccountKey=", "accountkey="][..], + 86, + "Az09+/", + '-', + "an Azure Storage account key", + ), + ( + &["AccountKey=", "accountkey="][..], + 86, + "Az09+/", + '_', + "an Azure Storage account key", + ), + ( + &["glpat-"][..], + 20, + "Az09_-", + '+', + "a GitLab personal access token", + ), + ( + &["glpat-"][..], + 20, + "Az09_-", + '/', + "a GitLab personal access token", + ), (&["npm_"][..], 36, "Az09", '_', "an npm access token"), (&["pypi-"][..], 85, "Az09_-", '.', "a PyPI API token"), + (&["pypi-"][..], 85, "Az09_-", '+', "a PyPI API token"), + (&["pypi-"][..], 85, "Az09_-", '/', "a PyPI API token"), (&["hf_"][..], 34, "Az09", '_', "a Hugging Face access token"), ]; for (prefixes, minimum, alphabet, invalid, label) in cases { @@ -531,6 +575,11 @@ mod tests { azure, "a `=` byte after the padding", ), + ( + format!("ghp_{AZURITE_ACCOUNT_KEY}"), + Some("a GitHub token"), + "a GitHub token that overlaps the key", + ), ( format!("{azurite} token={github}"), Some("a GitHub token"), From 7d5c7af113492a74f81615debff2ba62aadfa397 Mon Sep 17 00:00:00 2001 From: Antony Date: Tue, 24 Nov 2026 22:09:38 +0530 Subject: [PATCH 4/6] refactor(preflight): dedicated Azure check, case-insensitive keyword, no line copy --- src/preflight.rs | 104 +++++++++++++++++++++++------------------------ 1 file changed, 50 insertions(+), 54 deletions(-) diff --git a/src/preflight.rs b/src/preflight.rs index 5de34e1..b34b6b5 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -1,7 +1,5 @@ //! Local refusals before any patch bytes leave the checkout. -use std::borrow::Cow; - use crate::git::{LocalChanges, PatchPaths}; #[derive(Debug, thiserror::Error)] @@ -285,18 +283,6 @@ const TOKEN_SHAPES: &[TokenShape] = &[ minimum: 52, body: base32, }, - // https://learn.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string - // A real key is 88 - // characters including its `==` padding; the rule requires only the 86 - // base64 characters before it and does not check the padding. Connection - // string keywords are case-insensitive, but only these two casings are - // covered, because `has_token` matches prefixes exactly. - TokenShape { - kind: AZURE_ACCOUNT_KEY_KIND, - prefixes: &["AccountKey=", "accountkey="], - minimum: 86, - body: base64, - }, // https://docs.gitlab.com/user/profile/personal_access_tokens/ // `glpat-` followed by 20 characters. TokenShape { @@ -334,9 +320,6 @@ const TOKEN_SHAPES: &[TokenShape] = &[ }, ]; -/// The kind of the row that the Azurite exception applies to. -const AZURE_ACCOUNT_KEY_KIND: &str = "an Azure Storage account key"; - /// Azurite's well-known development account key for `devstoreaccount1`, which /// Microsoft publishes under "Use a well-known storage account and key" at /// . @@ -344,30 +327,46 @@ const AZURE_ACCOUNT_KEY_KIND: &str = "an Azure Storage account key"; const AZURITE_ACCOUNT_KEY: &str = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="; -/// `text` with each exact occurrence of [`AZURITE_ACCOUNT_KEY`] blanked by as -/// many spaces, so other offsets are unchanged. An occurrence inside a longer -/// key is a different key, so it stays: a base64 byte before it, or a base64 -/// or `=` byte after it, extends the key. A `=` before it ends a keyword such -/// as `AccountKey=`, because padding only ends a key. -fn without_azurite_key(text: &str) -> Cow<'_, str> { +/// The connection-string keyword that names a storage account key. Keywords +/// are ASCII case-insensitive, so it is compared that way, in place. +const ACCOUNT_KEY_KEYWORD: &[u8] = b"accountkey="; + +/// The base64 characters of a storage account key before its `==` padding. +const ACCOUNT_KEY_LENGTH: usize = 86; + +/// An Azure Storage account key: the `AccountKey=` keyword in any ASCII case, +/// followed by at least 86 base64 characters. A real key is 88 characters +/// including its `==` padding, which is not checked. Every candidate but the +/// exact Azurite key counts. Source: +/// . +fn has_account_key(text: &str) -> bool { let bytes = text.as_bytes(); - let mut exempt = Cow::Borrowed(text); - for (start, key) in text.match_indices(AZURITE_ACCOUNT_KEY) { - let end = start + key.len(); - let extended_before = start - .checked_sub(1) - .and_then(|index| bytes.get(index)) - .is_some_and(|byte| base64(*byte)); - let extended_after = bytes - .get(end) - .is_some_and(|byte| base64(*byte) || *byte == b'='); - if !extended_before && !extended_after { - exempt - .to_mut() - .replace_range(start..end, &" ".repeat(key.len())); - } - } - exempt + bytes + .windows(ACCOUNT_KEY_KEYWORD.len()) + .enumerate() + .filter(|(_, window)| window.eq_ignore_ascii_case(ACCOUNT_KEY_KEYWORD)) + .map(|(start, _)| start + ACCOUNT_KEY_KEYWORD.len()) + .any(|key| { + bytes + .iter() + .skip(key) + .take(ACCOUNT_KEY_LENGTH) + .take_while(|byte| base64(**byte)) + .count() + == ACCOUNT_KEY_LENGTH + && !is_azurite_key(bytes, key) + }) +} + +/// Whether the key at `start` is exactly [`AZURITE_ACCOUNT_KEY`]: the same +/// bytes, not extended by a base64 or `=` byte after them. A candidate always +/// follows the keyword's `=`, so no left boundary check is needed. +fn is_azurite_key(bytes: &[u8], start: usize) -> bool { + let end = start + AZURITE_ACCOUNT_KEY.len(); + let extended_after = bytes + .get(end) + .is_some_and(|byte| base64(*byte) || *byte == b'='); + bytes.get(start..end) == Some(AZURITE_ACCOUNT_KEY.as_bytes()) && !extended_after } /// Literal private-key markers and distinctive credential prefixes. This @@ -378,20 +377,12 @@ fn secret_shape(text: &str) -> Option<&'static str> { { return Some("a private-key marker"); } - let exempt = without_azurite_key(text); TOKEN_SHAPES .iter() - .find(|shape| { - // Only an account key can be the Azurite key. Every other family - // reads the original text, so a token that overlaps it still counts. - let text = if shape.kind == AZURE_ACCOUNT_KEY_KIND { - &*exempt - } else { - text - }; - has_token(text, shape.prefixes, shape.minimum, shape.body) - }) + .find(|shape| has_token(text, shape.prefixes, shape.minimum, shape.body)) .map(|shape| shape.kind) + // After every token shape, so their labels keep priority. + .or_else(|| has_account_key(text).then_some("an Azure Storage account key")) } #[cfg(test)] @@ -450,7 +441,7 @@ mod tests { "a Proofline token", ), ( - &["AccountKey=", "accountkey="][..], + &["AccountKey=", "accountkey=", "ACCOUNTKEY=", "accountKey="][..], 86, "Az09+/", '!', @@ -466,14 +457,14 @@ mod tests { // As for `ghs_`, the other base64 alphabet's punctuation is // invalid in each base64 family. ( - &["AccountKey=", "accountkey="][..], + &["AccountKey=", "accountkey=", "ACCOUNTKEY=", "accountKey="][..], 86, "Az09+/", '-', "an Azure Storage account key", ), ( - &["AccountKey=", "accountkey="][..], + &["AccountKey=", "accountkey=", "ACCOUNTKEY=", "accountKey="][..], 86, "Az09+/", '_', @@ -575,6 +566,11 @@ mod tests { azure, "a `=` byte after the padding", ), + ( + format!("AccountKey={AZURITE_ACCOUNT_KEY};AccountKey={AZURITE_ACCOUNT_KEY};"), + None, + "two exact Azurite keys on one line", + ), ( format!("ghp_{AZURITE_ACCOUNT_KEY}"), Some("a GitHub token"), From ab53f36cc5aba221c73b1815616147dc47887a59 Mon Sep 17 00:00:00 2001 From: Antony Date: Tue, 24 Nov 2026 23:34:42 +0530 Subject: [PATCH 5/6] test(preflight): pin AccountKey suffix matching and label priority; clarify minimum-length comments --- src/preflight.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/preflight.rs b/src/preflight.rs index b34b6b5..9e6d150 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -284,7 +284,7 @@ const TOKEN_SHAPES: &[TokenShape] = &[ body: base32, }, // https://docs.gitlab.com/user/profile/personal_access_tokens/ - // `glpat-` followed by 20 characters. + // A token is `glpat-` followed by 20 characters; the rule requires at least 20. TokenShape { kind: "a GitLab personal access token", prefixes: &["glpat-"], @@ -292,7 +292,7 @@ const TOKEN_SHAPES: &[TokenShape] = &[ body: base64url, }, // https://docs.npmjs.com/about-access-tokens - // `npm_` followed by 36 alphanumerics. + // A token is `npm_` followed by 36 alphanumerics; the rule requires at least 36. TokenShape { kind: "an npm access token", prefixes: &["npm_"], @@ -591,6 +591,32 @@ mod tests { } } + /// "Az09+/" cycled to 86 base64 characters, plus `==`: a non-Azurite key. + fn real_account_key() -> String { + format!( + "{}==", + "Az09+/".chars().cycle().take(86).collect::() + ) + } + + #[test] + fn a_field_name_ending_in_account_key_holds_an_account_key() { + // Suffix matching is deliberate: names such as `StorageAccountKey` + // hold real keys, so no boundary is required before the keyword. + let text = format!("StorageAccountKey={}", real_account_key()); + assert_eq!(secret_shape(&text), Some("an Azure Storage account key")); + } + + #[test] + fn a_token_label_takes_priority_over_an_account_key_on_the_same_line() { + let text = format!( + "AccountName=acme;AccountKey={}; token=ghp_{}", + real_account_key(), + "S".repeat(36) + ); + assert_eq!(secret_shape(&text), Some("a GitHub token")); + } + #[test] fn ordinary_text_has_no_secret_shape() { assert_eq!( From 5885131737b888d31ac390bc0148727f252305a0 Mon Sep 17 00:00:00 2001 From: Antony Date: Wed, 25 Nov 2026 00:16:45 +0530 Subject: [PATCH 6/6] test(preflight): non-exempt account key before an Azurite key --- src/preflight.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/preflight.rs b/src/preflight.rs index 9e6d150..d1f4925 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -586,6 +586,11 @@ mod tests { azure, "a real account key on the same line", ), + ( + format!("AccountName=acme;AccountKey={real}; {azurite}"), + azure, + "a real account key before an Azurite key on the same line", + ), ] { assert_eq!(secret_shape(&text), expected, "{case}"); }