Skip to content
Merged
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
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions atomic-cli/src/commands/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
//! 3. **Identity** — the server profile's `identity` field, if set, overrides
//! the global default identity.
//! 4. **Bearer token** — a short-lived, client-self-signed EdDSA JWT minted
//! for the resolved identity (see [`crate::commands::token`]). The raw
//! for the resolved identity (see [`atomic_remote::auth::token`]). The raw
//! public key is never sent as a credential.
//!
//! # Identity resolution
Expand Down Expand Up @@ -97,7 +97,7 @@ pub async fn build_apex_client(server_override: Option<&str>) -> CliResult<Stora

// Self-signed EdDSA JWT keyed by the identity's own public key; minted
// against the apex URL (the token is portable across the deployment).
let bearer_token = crate::commands::token::get_token(&apex_url, &identity).await?;
let bearer_token = atomic_remote::auth::token::get_token(&apex_url, &identity).await?;

let delegation = delegation_for(&identity, &apex_url);
let client =
Expand All @@ -120,7 +120,8 @@ fn delegation_for(identity: &atomic_identity::Identity, server: &str) -> Option<
return None;
}
let store = IdentityStore::open_default().ok()?;
let resolved = crate::commands::delegation::active_for(&store, identity, Some(server)).ok()?;
let resolved =
atomic_remote::auth::delegation::active_for(&store, identity, Some(server)).ok()?;
Some(atomic_canonical::delegation::encode_for_transport(
&resolved.document,
))
Expand Down Expand Up @@ -170,7 +171,7 @@ pub async fn build_apex_client_as(
server_override: Option<&str>,
) -> CliResult<(StorageClient, String)> {
let apex_url = apex_server_url(server_override)?;
let bearer_token = crate::commands::token::get_token(&apex_url, identity).await?;
let bearer_token = atomic_remote::auth::token::get_token(&apex_url, identity).await?;
let delegation = delegation_for(identity, &apex_url);

let client =
Expand Down Expand Up @@ -220,7 +221,7 @@ pub async fn build_client_with_org(
let identity = resolve_identity_for_server(server)?;

// Log in against the server apex for a JWT bearer token.
let bearer_token = crate::commands::token::get_token(&server_url, &identity).await?;
let bearer_token = atomic_remote::auth::token::get_token(&server_url, &identity).await?;

let client = StorageClient::new(&base_url, &org_slug, &bearer_token).map_err(|e| {
CliError::Internal(anyhow::anyhow!("Failed to create storage client: {}", e))
Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/clone/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ impl Clone {
.danger_accept_invalid_certs(self.insecure);

// Clone uses the URL directly — identity inferred from subdomain only.
crate::commands::auth::attach_identity(config, &self.url, None).await
atomic_remote::auth::attach_identity(config, &self.url, None).await
}

/// CB-10B Git-transport bootstrap (RFC §7.3/§8.6): `git clone` the
Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/identity/agent/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ use serde_json::json;
use atomic_identity::delegation::DelegationStatus;
use atomic_identity::{IdentityStore, IdentityType};

use crate::commands::delegation::{load_for_delegate, ResolvedDelegation};
use crate::commands::Command;
use crate::error::{CliError, CliResult};
use crate::output::print_hint;
use atomic_remote::auth::delegation::{load_for_delegate, ResolvedDelegation};

use super::humanize_remaining;

Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/identity/agent/renew.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ use atomic_identity::delegation::{Delegation, DelegationScope};
use atomic_identity::{Identity, IdentityStore};
use atomic_remote::storage_types::PushDelegationRequest;

use crate::commands::delegation::load_for_delegate;
use crate::commands::Command;
use crate::error::{CliError, CliResult};
use crate::output::{print_success, print_warning};
use atomic_remote::auth::delegation::load_for_delegate;

use super::{
humanize_remaining, parse_duration, parse_patterns, parse_permissions, DEFAULT_EXPIRY_DAYS,
Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/identity/agent/revoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ use atomic_canonical::delegation as cert;
use atomic_identity::IdentityStore;
use atomic_remote::storage_types::RevokeDelegationRequest;

use crate::commands::delegation::load_for_delegate;
use crate::commands::Command;
use crate::error::{CliError, CliResult};
use crate::output::{print_hint, print_success, print_warning};
use atomic_remote::auth::delegation::load_for_delegate;

/// Revoke an agent's delegation.
#[derive(Debug, Parser)]
Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/identity/agent/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ use clap::Parser;

use atomic_identity::IdentityStore;

use crate::commands::delegation::load_for_delegate;
use crate::commands::Command;
use crate::error::{CliError, CliResult};
use crate::output::{print_hint, print_warning};
use atomic_remote::auth::delegation::load_for_delegate;

use super::humanize_remaining;

Expand Down
3 changes: 0 additions & 3 deletions atomic-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@ pub mod view;
pub mod agent;

// Phase 3: Remote Commands
pub mod auth;
pub mod blame;
pub mod clone;
pub mod pull;
Expand All @@ -130,9 +129,7 @@ pub mod query;

// Storage management commands (always available)
pub mod client;
pub mod delegation;
pub mod project;
pub mod token;
pub mod workspace;
pub(crate) mod workspace_txn;

Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/pull/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ impl Pull {
.with_timeout(Duration::from_secs(self.timeout))
.danger_accept_invalid_certs(self.insecure);

crate::commands::auth::attach_identity(config, remote_url, identity_hint).await
atomic_remote::auth::attach_identity(config, remote_url, identity_hint).await
}

/// Display the dry run preview.
Expand Down
4 changes: 2 additions & 2 deletions atomic-cli/src/commands/push/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ impl Push {
.with_timeout(Duration::from_secs(self.timeout))
.danger_accept_invalid_certs(self.insecure);

crate::commands::auth::attach_identity(config, remote_url, identity_hint).await
atomic_remote::auth::attach_identity(config, remote_url, identity_hint).await
}

/// Display the dry run preview: per-view manifest sync plans.
Expand Down Expand Up @@ -569,7 +569,7 @@ impl Push {
// deliberately masked), which surfaces as a misleading "view not found".
// Catching the missing credential here gives the user an accurate,
// actionable error instead.
crate::commands::auth::check_push_credentials(&remote_url, identity_hint.as_deref())?;
atomic_remote::auth::check_push_credentials(&remote_url, identity_hint.as_deref())?;

// Build the local ancestor chain, root → leaf. A draft's parent must
// exist on the remote before the draft's manifest can reference it,
Expand Down
9 changes: 3 additions & 6 deletions atomic-cli/src/commands/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,9 @@ impl Repo {
CliError::Internal(anyhow::anyhow!("Failed to create async runtime: {e}"))
})?;
let (project_id, previous) = rt.block_on(async {
let config = crate::commands::auth::attach_identity(
HttpRemoteConfig::default(),
&entry.url,
None,
)
.await;
let config =
atomic_remote::auth::attach_identity(HttpRemoteConfig::default(), &entry.url, None)
.await;
let remote = HttpRemote::with_config(&entry.url, config).map_err(|e| {
CliError::InvalidArgument {
message: format!("cannot reach remote {}: {e}", entry.url),
Expand Down
5 changes: 3 additions & 2 deletions atomic-cli/src/commands/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5035,7 +5035,7 @@ fn sync_auth_headers(remote_url: &str, identity: Option<&str>) -> HashMap<String
.map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to create async runtime: {}", e)))
.ok();
let Some(rt) = rt else { return HashMap::new() };
let config = rt.block_on(crate::commands::auth::attach_identity(
let config = rt.block_on(atomic_remote::auth::attach_identity(
atomic_remote::HttpRemoteConfig::new(),
remote_url,
identity,
Expand Down Expand Up @@ -5142,7 +5142,7 @@ pub fn push(args: &super::push::Push) -> CliResult<bool> {
style_view(&remote_name),
hint(&remote_url)
);
crate::commands::auth::check_push_credentials(&remote_url, args.identity.as_deref())?;
atomic_remote::auth::check_push_credentials(&remote_url, args.identity.as_deref())?;
let auth_headers = sync_auth_headers(&remote_url, args.identity.as_deref());
stage_line("Connected");

Expand All @@ -5161,6 +5161,7 @@ pub fn push(args: &super::push::Push) -> CliResult<bool> {
timeout_secs: args.timeout,
auth_headers: auth_headers.clone(),
remote_url: Some(remote_url.clone()),
identity: args.identity.clone(),
};
let response = match session.push_changes(request) {
Ok(response) => response,
Expand Down
2 changes: 1 addition & 1 deletion atomic-cli/src/commands/view/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ use atomic_remote::{HttpRemote, HttpRemoteConfig, RemoteViewInfo};
use atomic_repository::repository::ViewInfo;
use atomic_repository::Repository;

use crate::commands::auth::attach_identity;
use crate::commands::{find_repository_root, Command};
use crate::error::{CliError, CliResult};
use crate::output::{hint, view as style_view};
use atomic_remote::auth::attach_identity;

/// Default request timeout (seconds) for the remote view listing.
const DEFAULT_TIMEOUT_SECS: u64 = 30;
Expand Down
38 changes: 38 additions & 0 deletions atomic-cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,20 @@ pub enum CliError {
Repository(#[from] atomic_repository::RepositoryError),
}

impl From<atomic_remote::auth::AuthError> for CliError {
fn from(error: atomic_remote::auth::AuthError) -> Self {
match error {
atomic_remote::auth::AuthError::Internal(error) => Self::Internal(error),
atomic_remote::auth::AuthError::AuthenticationFailed { remote } => {
Self::AuthenticationFailed { remote }
}
atomic_remote::auth::AuthError::DelegationError { message } => {
Self::DelegationError { message }
}
}
}
}

impl CliError {
// Constructor Helpers

Expand Down Expand Up @@ -745,6 +759,30 @@ impl CliError {
mod tests {
use super::*;

#[test]
fn shared_auth_errors_preserve_cli_categories_and_context() {
use atomic_remote::auth::AuthError;

let error = CliError::from(AuthError::Internal(anyhow::anyhow!("key store failure")));
assert!(
matches!(&error, CliError::Internal(source) if source.to_string() == "key store failure")
);

let error = CliError::from(AuthError::AuthenticationFailed {
remote: "https://example.com: missing signing key".into(),
});
assert!(
matches!(&error, CliError::AuthenticationFailed { remote } if remote == "https://example.com: missing signing key")
);

let error = CliError::from(AuthError::DelegationError {
message: "certificate expired; renew it".into(),
});
assert!(
matches!(&error, CliError::DelegationError { message } if message == "certificate expired; renew it")
);
}

// -------------------------------------------------------------------------
// Error Display Tests
// -------------------------------------------------------------------------
Expand Down
5 changes: 4 additions & 1 deletion atomic-remote/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ categories = ["development-tools"]
# Internal crates
atomic-core = { workspace = true }
atomic-objects = { workspace = true }
atomic-config = { workspace = true }

# HTTP client
reqwest = { workspace = true, features = ["json", "gzip", "deflate", "stream"] }
Expand All @@ -35,12 +36,13 @@ anyhow = { workspace = true }
url = { workspace = true }
bytes = { workspace = true }
log = { workspace = true }
data-encoding = { workspace = true }

# Time
chrono = { workspace = true }

# IDs
uuid = { version = "1.0", features = ["serde"] }
uuid = { version = "1.0", features = ["serde", "v4"] }

# URL encoding
urlencoding = "2"
Expand All @@ -52,6 +54,7 @@ atomic-identity = { workspace = true }
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
tempfile = { workspace = true }
env_logger = { workspace = true }
serial_test = { workspace = true }

[features]
default = []
Expand Down
42 changes: 42 additions & 0 deletions atomic-remote/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ communicate with `atomic-api` servers.
- Storage management APIs for workspaces and projects.
- Error types with retry/auth/not-found classification and user-facing suggestions.
- Streaming push/pull support for chunked remote transfers.
- Shared local identity resolution, self-signed JWTs, and agent delegation for
CLI and trusted native callers (`auth`, `auth::token`, `auth::delegation`).

## Usage

Expand All @@ -29,6 +31,46 @@ async fn example() -> Result<(), Box<dyn std::error::Error>> {
}
```

## Local authentication

Repository clients share one local authentication policy rather than minting tokens
in an RPC handler or passing signing keys through RPC:

```rust,ignore
use atomic_remote::{auth, HttpRemote, HttpRemoteConfig};

async fn authenticated_remote(
url: &str,
identity: Option<&str>,
) -> Result<HttpRemote, Box<dyn std::error::Error>> {
// Pushes fail before network I/O when no identity/signing key is usable.
// Omit this preflight for reads that may be publicly accessible.
auth::check_push_credentials(url, identity)?;
let config = auth::attach_identity(HttpRemoteConfig::new(), url, identity).await;
Ok(HttpRemote::with_config(url, config)?)
}
```

Identity precedence is explicit override, nonempty `ATOMIC_AGENT_IDENTITY`, URL
userinfo, configured server binding (longest host suffix, active profile wins ties;
agent binding preferred), then the legacy leading subdomain label. Missing inferred
identities fall back to the store's default; a missing explicit override never does.
Callers resolve the configured remote URL and pass its identity binding only when
no explicit override was supplied.

`attach_identity` signs a fresh five-minute EdDSA JWT locally and presents an agent's
verified delegation certificate when applicable. It leaves the config unchanged on
authentication failure so public reads remain possible. Delegation resolution keeps
the existing environment-grant precedence, signature, expiry, local revocation,
and scope semantics; the server remains authoritative for remote revocations.
`AuthError` distinguishes `Internal`, `AuthenticationFailed { remote }`, and
`DelegationError { message }` so callers can preserve their error categories.

Identity/config/key/delegation access is synchronous local filesystem work even
though token attachment has an async API. Async services should run this trusted
local credential preparation on a blocking thread; network-facing handlers should
receive prepared transport credentials, not read ambient local identities.

## Feature flags

- `integration-tests`: enables integration tests that require a running
Expand Down
Loading
Loading