Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,9 @@ fleet pays the WAN cost, the rest are served locally. The upstream LFS transfer
in-process over HTTPS (reqwest + rustls, no OpenSSL), so the binary stays statically
linked. Cached objects share the `--cache-max-mb` budget and LRU eviction with the
git mirrors. No configuration is needed: LFS is served on the same endpoints the git
client already routes through the proxy.
client already routes through the proxy. With `--lfs-batch-cache-fallback`, a batch
whose upstream call fails transiently is answered from the cache when every
object in it is cached (see [Auth model](./security.md#auth-model) for where that is allowed).

### Cache management

Expand Down
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Every flag has an environment-variable equivalent.
| `--auth-ttl-seconds` | `GITCACHEPROXY_AUTH_TTL_SECONDS` | `0` | Reuse a validation verdict per `(credential, repo)` for this many seconds, so the requests of one clone, or repeated submodule fetches, validate once (`0` = validate every request) |
| `--auth-max-concurrent` | `GITCACHEPROXY_AUTH_MAX_CONCURRENT` | `32` | Max token-validation requests in flight; a check waits up to `--auth-timeout-seconds` for a slot, then fails with 503 (`0` = unlimited) |
| `--auth-allow-http` | `GITCACHEPROXY_AUTH_ALLOW_HTTP` | `false` | Provider modes: accept a plain `http://` validation endpoint, which sends client credentials in cleartext |
| `--lfs-batch-cache-fallback` | `GITCACHEPROXY_LFS_BATCH_CACHE_FALLBACK` | `false` | When the upstream LFS batch fails transiently (no response or a 5xx), answer a download batch whose objects are all cached. Requires `--upstream-credential static` and `--auth-provider none` or `shared` (see [Auth model](./security.md#auth-model)) |
| `--upstream-timeout-seconds` | `GITCACHEPROXY_UPSTREAM_TIMEOUT_SECONDS` | `3600` | Total seconds per upstream clone, full-ref fetch or SHA backfill, including all attempts and retry delays (must be positive) |
| `--fetch-ttl-seconds` | `GITCACHEPROXY_FETCH_TTL_SECONDS` | `10` | Skip upstream fetch if the last one started within this window (`0` = always fetch) |
| `--refresh-interval-seconds` | `GITCACHEPROXY_REFRESH_INTERVAL_SECONDS` | `0` | Background refresh round spacing; 0 disables it, otherwise at least 3600 |
Expand Down
4 changes: 3 additions & 1 deletion docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ Label values:
`serve_duration_seconds`: `info_refs` (the buffered ref advertisement) or
`upload_pack` (the packfile stream, timed to EOF).
- `result` on `requests_total`: `ok`, `error`, `upstream_error`, `unauthorized`,
`rejected`. On `upstream_ops_total`: `ok` or `error`. On `lfs_objects_total`:
`rejected`, `cache_fallback` (an `lfs_batch` answered from the cache after a

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`rejected`, `cache_fallback` (an `lfs_batch` answered from the cache after a
`rejected`, `cached_on_error` (an `lfs_batch` answered from the cache after a

transient upstream failure, see `--lfs-batch-cache-fallback`). On
`upstream_ops_total`: `ok` or `error`. On `lfs_objects_total`:
`hit` (served from disk), `miss` (fetched from upstream, then cached), `error`.
On `auth_validations_total`: `allow`, `deny`, `unavailable` (the endpoint
failed, throttled, or answered something else), `saturated` (no call made: no
Expand Down
6 changes: 6 additions & 0 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ cannot fetch another repo's object from the shared object cache. Every replica
behind one address must share `--auth-signing-key`, or a grant issued by one
is refused by the others; the caches themselves stay independent.

That repo binding relies on the upstream batch to confirm an object belongs to
the repo, which is why `--lfs-batch-cache-fallback` (answering a batch from the
cache while upstream is down) is refused at startup with a provider mode or
`--upstream-credential client`. With `none` or `shared` auth any client can
already GET any cached object, so the fallback grants nothing new.

### Fetch upstream with the client's credential (`--upstream-credential client`)

In the default `static` mode the proxy clones and fetches upstream with the one
Expand Down
71 changes: 71 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,30 @@ pub fn validate_upstream_credential(
Ok(())
}

/// Reject a `--lfs-batch-cache-fallback` that would bypass an authorization
/// check. In `client` upstream-credential mode the upstream batch runs on the
/// client's own credential, so it is what authorizes the client. Under a
/// `github`/`gitlab`/`custom` provider a batch grant binds an object to the
/// validated repo, and only the upstream batch confirms the object belongs to
/// that repo; the cache is shared across repos, so a fallback would let a
/// client reach another repo's cached object by its oid.
pub fn validate_lfs_batch_cache_fallback(
enabled: bool,
mode: UpstreamCredential,
provider: AuthProvider,
) -> Result<()> {
if !enabled {
return Ok(());
}
if mode != UpstreamCredential::Static {
bail!("--lfs-batch-cache-fallback requires --upstream-credential static");
}
if !matches!(provider, AuthProvider::None | AuthProvider::Shared) {
bail!("--lfs-batch-cache-fallback requires --auth-provider none or shared, not {provider}");
}
Ok(())
}

#[derive(Parser, Debug, Clone)]
#[command(
name = "git-cache-proxy",
Expand Down Expand Up @@ -214,6 +238,13 @@ pub struct Config {
#[arg(long, env = "GITCACHEPROXY_AUTH_TTL_SECONDS", default_value_t = 0)]
pub auth_ttl_seconds: u64,

/// Answer an LFS download batch from the cache when the upstream batch fails
/// transiently (no response, or a 5xx). Requires `--upstream-credential static`
/// and `--auth-provider none` or `shared`, where the upstream batch authorizes
/// nothing the client could not already reach.
#[arg(long, env = "GITCACHEPROXY_LFS_BATCH_CACHE_FALLBACK")]
pub lfs_batch_cache_fallback: bool,

/// Total seconds per upstream clone, full-ref fetch or SHA backfill,
/// including all attempts and retry delays. Must be positive.
#[arg(long, env = "GITCACHEPROXY_UPSTREAM_TIMEOUT_SECONDS", default_value = "3600",
Expand Down Expand Up @@ -429,6 +460,46 @@ mod tests {
}
}

#[test]
fn lfs_batch_cache_fallback_needs_static_mode_and_no_per_repo_auth() {
let all = [
AuthProvider::None,
AuthProvider::Shared,
AuthProvider::Github,
AuthProvider::Gitlab,
AuthProvider::Custom,
];
for provider in all {
for mode in [UpstreamCredential::Static, UpstreamCredential::Client] {
assert!(validate_lfs_batch_cache_fallback(false, mode, provider).is_ok());
}
}
for provider in [AuthProvider::None, AuthProvider::Shared] {
assert!(
validate_lfs_batch_cache_fallback(true, UpstreamCredential::Static, provider)
.is_ok()
);
}
let err = validate_lfs_batch_cache_fallback(
true,
UpstreamCredential::Client,
AuthProvider::Github,
)
.unwrap_err()
.to_string();
assert!(err.contains("--upstream-credential static"), "{err}");
for provider in [
AuthProvider::Github,
AuthProvider::Gitlab,
AuthProvider::Custom,
] {
let err = validate_lfs_batch_cache_fallback(true, UpstreamCredential::Static, provider)
.unwrap_err()
.to_string();
assert!(err.contains("--auth-provider"), "{err}");
}
}

#[test]
fn client_mode_rejects_a_static_auth_header() {
let err =
Expand Down
94 changes: 91 additions & 3 deletions src/lfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
//! Flow:
//! POST <repo>/info/lfs/objects/batch
//! -> forward to upstream, then rewrite every download href to point back here
//! (`<repo>/info/lfs/objects/<oid>`) so the object fetch is cached.
//! (`<repo>/info/lfs/objects/<oid>`) so the object fetch is cached. With
//! `--lfs-batch-cache-fallback`, a transient upstream failure is answered
//! locally when every requested object is cached (see `Lfs::cached_batch`).
//! GET <repo>/info/lfs/objects/<oid>
//! -> serve from the on-disk cache (content-addressed by oid), or on a miss fetch
//! it once (re-batch for a fresh authorized URL, download, verify sha256 ==
Expand Down Expand Up @@ -85,6 +87,8 @@ pub struct Lfs {
/// Names the per-download temp file the object is streamed to before its atomic
/// rename into the content-addressed cache path.
tmp_counter: AtomicU64,
/// Whether a transiently failed download batch may be answered from the cache.
batch_cache_fallback: bool,
}

impl Lfs {
Expand All @@ -102,9 +106,18 @@ impl Lfs {
index,
slots: Mutex::new(HashMap::new()),
tmp_counter: AtomicU64::new(0),
batch_cache_fallback: false,
}
}

/// Allow `cached_batch` to answer a download batch whose upstream call failed
/// transiently. Startup validation (`validate_lfs_batch_cache_fallback`) only
/// allows it where the upstream batch authorizes nothing.
pub fn with_batch_cache_fallback(mut self, enabled: bool) -> Self {
self.batch_cache_fallback = enabled;
self
}

/// Proxy a client batch request to upstream and rewrite the download hrefs so the
/// objects are fetched back through this proxy (and thus cached). `advertise_base`
/// is the proxy's own `scheme://host` as the client reached it, and `grant`
Expand All @@ -128,6 +141,59 @@ impl Lfs {
serde_json::to_vec(&json).context("serialize lfs batch response")
}

/// Answer a download batch from the cache alone after the upstream batch failed
/// with `err`. Each object gets the same download action `batch` would produce,
/// so its GET is a plain cache hit. Objects are content-addressed and
/// hash-verified on store, so a cached one is never stale. `None`, leaving the
/// caller to fail the batch, when the fallback is off, `err` is not transient,
/// the request is not a well-formed basic-transfer download batch, or any
/// requested object is not cached: the client would need upstream for it anyway.
pub async fn cached_batch(
&self,
err: &anyhow::Error,
repo: &str,
body: &[u8],
advertise_base: &str,
grant: impl Fn(&str, u64) -> Option<DownloadGrant>,
) -> Option<Vec<u8>> {
if !self.batch_cache_fallback || !is_transient_batch_error(err) {
return None;
}
let req: Value = serde_json::from_slice(body).ok()?;
if req.get("operation")?.as_str()? != "download" {
return None;
}
// An omitted list means basic; otherwise the client must offer it.
if let Some(transfers) = req.get("transfers")
&& !transfers.as_array()?.iter().any(|t| t == "basic")
{
return None;
}
let mut objects = Vec::new();
for obj in req.get("objects")?.as_array()? {
let oid = obj.get("oid")?.as_str()?;
let size = obj.get("size")?.as_u64()?;
if !repo::valid_lfs_oid(oid)
|| !self
.cached(&repo::lfs_object_path(&self.cfg.cache_root, oid))
.await
{
return None;
}
// `authenticated`: the href carries its own credential, so git-lfs
// would otherwise prompt for one on the proxy href.
objects.push(serde_json::json!({
"oid": oid,
"size": size,
"authenticated": true,
"actions": { "download": { "href": "" } },
}));
}
let mut json = serde_json::json!({ "transfer": "basic", "objects": objects });
rewrite_download_hrefs(&mut json, advertise_base, repo, grant);
serde_json::to_vec(&json).ok()
}

/// Ensure the object identified by `oid` is on disk and return its path plus
/// whether it was a cache hit. On a miss `size` is required (the upstream batch
/// API needs it); it is not needed for a hit.
Expand Down Expand Up @@ -247,13 +313,22 @@ impl Lfs {
{
req = req.header(name, value);
}
// URLs are dropped from errors: they are logged, and an upstream base may
// carry userinfo.
let resp = req
.send()
.await
.map_err(reqwest::Error::without_url)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could also define our own error type, e.g.:

#[derive(Debug)]                                                                             
pub enum UpstreamBatchError {                                                                
    Status(StatusCode),                                                                      
    Network(String),                                                                         
}

impl std::fmt::Display for UpstreamBatchError {                                              
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Status(code) => write!(f, "upstream batch status: {code}"),
            Self::Transport(msg) => write!(f, "upstream batch transport error: {msg}"),
        }
    }
}
                                                                                                 
impl std::error::Error for UpstreamBatchError {}

impl From<reqwest::Error> for UpstreamBatchError {                                           
    fn from(err: reqwest::Error) -> Self {
        // Strip the URL once here
        let err = err.without_url();
        match err.status() {
            Some(status) => Self::Status(status),
            None => Self::Transport(err.to_string()),
        }
    }
}

impl UpstreamBatchError {                                                                    
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Status(status) => status.is_server_error(), // 5xx
            Self::Transport(_) => true, // connection failure, timeout, etc.
        }
    }
}

Then we can drop the mapping. This would be more idiomatic, though, more code.

.context("send lfs batch")?
.error_for_status()
.map_err(reqwest::Error::without_url)
.context("lfs batch http status")?;
Ok(resp.bytes().await.context("read lfs batch body")?.to_vec())
Ok(resp
.bytes()
.await
.map_err(reqwest::Error::without_url)
.context("read lfs batch body")?
.to_vec())
}

/// Stream an object href to `out`, sending the batch-supplied `headers`. reqwest
Expand Down Expand Up @@ -304,11 +379,24 @@ impl Lfs {
}
}

/// Whether an upstream batch failure is transient: a connect or send failure, a
/// body cut short, or a 5xx. A 4xx is upstream's answer about the
/// repo or credential and must not be papered over, nor a malformed 2xx body.
fn is_transient_batch_error(err: &anyhow::Error) -> bool {
err.chain()
.find_map(|e| e.downcast_ref::<reqwest::Error>())
.is_some_and(|e| match e.status() {
Some(status) => status.is_server_error(),
None => !e.is_builder() && !e.is_redirect(),
})
}

/// Rewrite each object's `download` href to point back at this proxy so the fetch is
/// cached, and set the object GET's credential from `grant` (or drop it when the
/// proxy serves anonymously) - the client authenticates to the proxy, not upstream.
/// Objects carrying an `error`, or an `upload` action, are left untouched, so a
/// grant is only ever issued for an object upstream listed for `repo`.
/// grant is only ever issued for an object upstream listed for `repo`, or, with
/// `--lfs-batch-cache-fallback` (only under `none`/`shared` auth), one already cached.
/// Malformed entries are skipped rather than failing the batch.
fn rewrite_download_hrefs(
json: &mut Value,
Expand Down
27 changes: 18 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use clap::Parser;
use tracing_subscriber::EnvFilter;

use git_cache_proxy::config::{
Config, LogFormat, UpstreamCredential, validate_upstream_credential,
Config, LogFormat, UpstreamCredential, validate_lfs_batch_cache_fallback,
validate_upstream_credential,
};
use git_cache_proxy::{auth, evict, git, lfs, metrics, repo, server};

Expand Down Expand Up @@ -48,6 +49,11 @@ async fn main() -> Result<()> {
cfg.auth_provider,
upstream_auth_header.is_some(),
)?;
validate_lfs_batch_cache_fallback(
cfg.lfs_batch_cache_fallback,
cfg.upstream_credential,
cfg.auth_provider,
)?;
match cfg.upstream_credential {
UpstreamCredential::Client => tracing::info!(
"upstream credential: forwarding each request's client credential; \
Expand Down Expand Up @@ -127,14 +133,17 @@ async fn main() -> Result<()> {
)
.await;

let lfs = Arc::new(lfs::Lfs::new(
lfs::LfsConfig {
upstream_base: upstream_base.clone(),
cache_root: cfg.cache_root.clone(),
upstream_auth_header,
},
index.clone(),
));
let lfs = Arc::new(
lfs::Lfs::new(
lfs::LfsConfig {
upstream_base: upstream_base.clone(),
cache_root: cfg.cache_root.clone(),
upstream_auth_header,
},
index.clone(),
)
.with_batch_cache_fallback(cfg.lfs_batch_cache_fallback),

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just pass this with the LfsConfig.

);

let state = server::AppState {
cache: cache.clone(),
Expand Down
7 changes: 5 additions & 2 deletions src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ pub enum Status {
UpstreamError,
Unauthorized,
Rejected,
/// An LFS batch upstream failed transiently, answered from the cache.
CacheFallback,
}

/// The `op` label on `upstream_ops_total` / `upstream_duration_seconds`.
Expand Down Expand Up @@ -115,6 +117,7 @@ impl Status {
Self::UpstreamError => "upstream_error",
Self::Unauthorized => "unauthorized",
Self::Rejected => "rejected",
Self::CacheFallback => "cache_fallback",
}
}
}
Expand Down Expand Up @@ -163,8 +166,8 @@ pub struct Metrics {
pub registry: Registry,
/// `requests_total{kind, result, repo}` - kind = info_refs | upload_pack |
/// auth | receive_pack | lfs_batch | lfs_object; result = ok | error |
/// upstream_error | unauthorized | rejected; repo = the served repo path when
/// result = ok, else `-`.
/// upstream_error | unauthorized | rejected | cache_fallback; repo = the served
/// repo path when result = ok, else `-`.
requests: IntCounterVec,
/// `upstream_ops_total{op, result, repo}` - op = clone | fetch | want_fetch;
/// result = ok | error; repo = the repo path when result = ok, else `-`.
Expand Down
Loading
Loading