Skip to content

Client Setup

The root hubuum_client::Client is asynchronous. Blocking users can use hubuum_client::blocking::Client.

It is safe to clone() an authenticated client when multiple parts of an application need to share the same API session.

Async Client

use hubuum_client::{Client, Credentials, Token};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::from_url("https://server.example.com:443")?;
    let client = client
        .login_session(Credentials::new("foo", "secret"), Default::default())
        .await?;

    // Token login is also supported:
    // let client = client.login_with_token(Token::new("my-token")).await?;

    Ok(())
}

Blocking Client

use hubuum_client::{blocking, Credentials, Token};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = blocking::Client::from_url("https://server.example.com:443")?;
    let client = client.login_session(Credentials::new("foo", "secret"), Default::default())?;

    // Token login is also supported:
    // let client = client.login_with_token(Token::new("my-token"))?;

    Ok(())
}

Builder Options

Use the builder when the default reqwest client configuration is not enough:

use std::time::Duration;

use hubuum_client::Client;

let client = Client::builder_from_url("https://server.example.com:443")?
    .validate_certs(true)
    .timeout(Duration::from_secs(30))
    .user_agent("inventory-sync/1.0")
    .max_response_body_bytes(8 * 1024 * 1024)
    .max_error_body_bytes(32 * 1024)
    .auto_pagination_limits(1_000, 100_000)
    .build()?;

The blocking client exposes the same builder methods through hubuum_client::blocking::Client::builder_from_url(...).

For local development against a server with a self-signed certificate, prefer the builder form so the exception is explicit:

let client = Client::builder_from_url("https://localhost:8443")?
    .validate_certs(false)
    .build()?;

Use BaseUrl::new(...) when a parsed URL is shared between clients. Base URLs must use HTTP(S), may include a path prefix, and reject embedded credentials, query parameters, and fragments. Client::try_new(base_url) is the fallible constructor for an already parsed URL. The older panicking constructors are deprecated.

Authenticated clients expose token(), base_url(), and http_client() accessors. Secret-bearing authentication and remote-target values redact their Debug output. Transport debug logs report request URLs, response status, and body size without logging request or response bodies.

login() borrows the unauthenticated client, so it can be reused for credential rotation. logout() consumes an authenticated client and returns an unauthenticated client, preventing accidental reuse of a revoked session at compile time. authenticate(token) attaches a token without a validation call; it is intended for custom transports and environments where the first API call is the validation boundary.

Credential creation and renewal on newer servers can additionally require fresh password approval. Use an unscoped human session and collect that human's current password when a mutation error's is_reauthentication_required() method returns true. Token login alone does not satisfy fresh authentication. The guide includes async and blocking flows that also work with older servers.

Rotating interactive sessions

For a server implementing the versioned session API, opt in explicitly:

```rust,ignore use hubuum_client::{Client, Credentials, SessionClientId};

let client = Client::builder_from_url("https://hubuum.example")?.build()? .login_session(Credentials::new("admin", password), SessionClientId::default()) .await?; let me = client.me().await?; ```

The blocking client exposes the same methods without .await. Clones share credentials and serialize refresh. Every ordinary, raw, and streaming request refreshes before the access deadline; the fixed absolute deadline never slides. A failed or cancelled single-use exchange clears the usable pair, including across clones, and returns ApiError::SessionExpired on later requests. Sign in again rather than retrying an old refresh token. No password is retained, and login_session keeps credentials only in memory. For persistence, explicitly supply an application-owned SessionStore to login_session_with_store, then use resume_session on subsequent starts. Both methods are available in async and blocking modes. resume_session validates the access token and refreshes it when needed; an empty or expired store returns None.

The store must isolate identities, protect serialized StoredSession values as secrets, and provide an exclusive cross-process SessionStoreGuard. Its save operation must atomically and durably replace the current value. The SDK binds snapshots to the API base URL and client ID; the application must additionally separate usernames and identity providers. Async clients acquire the store lock on a blocking worker so a contended filesystem lock cannot block the runtime. Guard reads and writes are synchronous and should be brief.

Every authenticated request reloads the latest stored state under that lock. Clients remain bound to the session family they logged into or resumed. If a new login replaces that family in the store, older clients return ApiError::SessionExpired; their logout cleanup preserves the newer login. Before refresh, the SDK durably removes the old credential; after successful exchange it durably saves the successor before using it. Crash, cancellation, refresh rejection, or an uncertain exchange leaves no reusable refresh secret and requires sign-in again. Logout clears the matching saved session. Transient validation errors preserve the cache; rejected credentials clear it. Store failures are returned to the caller and must not expose credential contents. Passwords are never included in snapshots, and Debug redacts all session data.

session_info() returns non-secret metadata. token() now returns a redacted, owned Result<Token, ApiError> snapshot because rotation cannot safely expose a stable borrowed token. Use client.token()?.as_str() only where raw access is necessary, and do not cache that snapshot across refresh. token_expires_at() returns an owned timestamp. During refresh the synchronous snapshot accessor can return SessionExpired; normal API calls wait for the coordinated result.

Legacy login() remains available only for older servers. The declared v0.0.20 target requires login_session() for interactive password login. Explicit authenticate(Token::new(...)) remains appropriate for PATs and service credentials. Session login uses the supported /api/v1/auth server contract; there is no silent password-based fallback or automatic downgrade. Logout of a session revokes its family, and logout-all preserves independent PATs according to the new server contract. Credential creation still uses fresh password approval through credential_approvals().