Rust

Auth

Password hashing, proofs, session stores, JWT issuers and verifiers, OAuth2 server values and WebAuthn passkeys.
Rust 7,997 lines (5,571 code)split
PartCodeCommentsBlankTotalFiles
Rust source5,5711,8266007,99738
Rust tests131691465

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-auth = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Auth, each a complete program you can copy and run.

Authentication needs a handful of primitives that must agree byte for byte with what is already stored: password hashes, one-time secrets, signed tokens and session data. This guide covers the common tasks.

Hash and verify a password

A Password proof hashes with Argon2 by default and verifies a candidate against a stored hash. Hashes are salted, so hashing the same password twice gives two different strings.

Rust
use utopia_auth::proofs::{Password, Proof};

let password = Password::new();
let hash = password.hash(b"correct horse battery staple")?;

assert!(hash.starts_with(b"$argon2id$"));
assert!(password.verify(b"correct horse battery staple", &hash)?);
assert!(!password.verify(b"wrong", &hash)?);

Verify a hash imported from another system

Users imported from elsewhere keep their hash and the options it was made with. Rebuild the algorithm from its name and stored options, then verify as usual.

Rust
use php_std::{Array, ArrayKey, Value};
use utopia_auth::proofs::Password;

let mut options = Array::new();
options.set(ArrayKey::from("version"), Value::from("sha256"));
let sha = Password::create_hash("sha", &options)?;

let stored = b"5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8";
assert!(sha.verify(b"password", stored)?);

Send a one-time code

Code generates numeric codes for emails and SMS, Token long random tokens for links. Store only the hash; verify what the user sends back.

Rust
use utopia_auth::proofs::{Code, Proof};

let code = Code::new(6)?;
let secret = code.generate()?;
assert_eq!(secret.len(), 6);
assert!(secret.iter().all(u8::is_ascii_digit));

let stored = code.hash(&secret)?;
assert!(code.verify(&secret, &stored)?);

A Store carries a few properties as base64 JSON, the format Appwrite's session cookies use. Decoding merges the properties back.

Rust
use php_std::Value;
use utopia_auth::Store;

let mut store = Store::new();
store.set_property(b"id", Value::from("session-1")).set_property(b"secret", Value::from("s3cr3t"));
let cookie = store.encode()?;
assert_eq!(cookie, "eyJpZCI6InNlc3Npb24tMSIsInNlY3JldCI6InMzY3IzdCJ9");

let mut read = Store::new();
read.decode(cookie.as_bytes());
assert_eq!(read.property(b"secret"), Some(&Value::from("s3cr3t")));

Issue and verify a JWT

A Jwt issuer signs claims with a shared secret (HS256); a Verifier checks the signature, the issuer, the audience and the expiry. Both take the current time, so tokens are testable.

Rust
use php_std::{Array, ArrayKey, Value};
use utopia_auth::jwt::{Audience, Hs256, Jwt, Symmetric, Verifier};

let secret = b"a-long-random-secret";
let issuer = Jwt(Symmetric::new(secret, b"https://cloud.example", None)?);
let audience = Audience::One(b"my-app".to_vec());

let mut claims = Array::new();
claims.set(ArrayKey::from("userId"), Value::from("u1"));
let now = 1_700_000_000;
let token = issuer.issue(&audience, 900, &claims, now)?;

let verifier = Verifier::new(Hs256::new(secret)?, Some(b"https://cloud.example"), Some(&audience), None, false, 0)?;
let verified = verifier.verify(token.as_bytes(), now + 60)?;
assert_eq!(verified.get_str("userId"), Some(&Value::from("u1")));
assert_eq!(verified.get_str("exp"), Some(&Value::Int(now + 900)));

// Fifteen minutes later the token has expired.
assert!(verifier.verify(token.as_bytes(), now + 901).is_err());

Sign access tokens with a key file

Access tokens are signed with an RSA key (RS256) so anyone holding the public key can verify them. Keys can be given inline as PEM or as a file:// path, which is read when signing.

Rust
use php_std::Array;
use utopia_auth::jwt::{generate_key_pair, AccessToken, Asymmetric, Rs256, Verifier};

let pair = generate_key_pair(2048)?;
let dir = std::env::temp_dir().join(format!("utopia-auth-guide-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("private.pem");
std::fs::write(&path, &pair.private_key).unwrap();

let private_key = format!("file://{}", path.display());
let issuer = AccessToken(Asymmetric::new(private_key.as_bytes(), pair.public_key.as_bytes(), b"https://cloud.example", None)?);
let audience = Array::from_list(vec!["https://api.example".into()]);
let now = 1_700_000_000;
let token = issuer.issue(b"user-1", &audience, b"client-1", now, 3600, &[b"read".to_vec()], None, &Array::new(), now)?;

let verifier = Verifier::new(Rs256::new(pair.public_key.as_bytes())?, None, None, Some(b"at+jwt"), false, 0)?;
let claims = verifier.verify(token.as_bytes(), now)?;
assert_eq!(claims.get_str("scope"), Some(&"read".into()));
std::fs::remove_dir_all(&dir).unwrap();

Reference#

Authentication primitives: password hashes, one-time secrets, signed JWTs, session stores, OAuth2 request values and passkey ceremonies.

Every value is stored byte for byte as other implementations of the same library store it, so hashes, tokens and sessions written by one can be read by the other.

Values are bytes (&[u8]), and free-form documents (hash options, JWT claims, client metadata) are php_std::Array and php_std::Value. Nothing reads the clock: functions that depend on the time take now (Unix seconds). Hashing is CPU bound, so async callers run it on the blocking pool. JWT keys are PEM, inline or as a file:// path, of any type and curve OpenSSL reads.

Hash a password and check it later
Rust
use utopia_auth::Hash;
use utopia_auth::hashes::Bcrypt;

let mut bcrypt = Bcrypt::new();
bcrypt.set_cost(10)?;
let hash = bcrypt.hash(b"secret")?;
assert!(hash.starts_with(b"$2y$10$"));
assert!(bcrypt.verify(b"secret", &hash)?);

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

errorinternal
The error type every fallible operation in the crate returns.
hashinternal
The password hash trait, and the constant-time comparison and secure randomness the hashes and proofs share.
hashes::argon2internal
The Argon2id password hash.
hashes::bcryptinternal
The bcrypt password hash.
hashes::md5internal
The unsalted MD5 digest, for imported legacy passwords.
hashes0 items
The built-in password hashing algorithms, each a `Hash`(crate::Hash) with its own options.
hashes::passwordinternal
The shared bcrypt, Argon2id and crypt calls behind the hashes: the options they read and the random salt they draw.
hashes::phpassinternal
The phpass password hash used by WordPress and phpBB.
hashes::plaintextinternal
A hash that stores the password as is.
hashes::scryptinternal
The scrypt password hash.
hashes::scrypt_modifiedinternal
Firebase's modified scrypt password hash.
hashes::shainternal
Unsalted SHA-1, SHA-2 and SHA-3 digests, for imported legacy passwords.
jwt::issuerinternal
JWT issuers: HS256 with a shared secret, RS256 with an RSA key pair, and the token kinds built on them.
jwt::keyinternal
Signing keys: PEM keys read inline or from a `file://` path, RSA key pair generation, and signing on OpenSSL with constant-time private key operations.
jwt4 items
Signed JSON Web Tokens (compact JWS, RFC 7515): issuers that sign claims with HS256 or RS256, and a verifier that checks the signature and the registered claims.
jwt::verifierinternal
JWT verification: the signature checks and the verifier of registered claims.
oauth2::authorization_detailsinternal
Rich authorization requests: the `authorization_details` parameter (RFC 9396).
oauth2::client_id_metadata_documentinternal
Client ID Metadata Documents: the metadata an OAuth2 client publishes at its client identifier URL.
oauth2::client_identifier_urlinternal
Client identifier URLs: OAuth2 clients identified by the URL of their metadata document.
oauth22 items
Request values an OAuth2 / OpenID Connect authorization server parses and checks: prompts, redirect URIs, resource indicators, authorization details, pushed authorization requests and client metadata documents.
oauth2::parinternal
Pushed authorization request URIs (RFC 9126).
oauth2::promptsinternal
The parsed OpenID Connect `prompt` request parameter.
oauth2::redirect_urisinternal
A client's registered redirect URIs and how a presented one matches.
oauth2::resource_indicatorsinternal
Resource indicators: the `resource` request parameter (RFC 8707).
optionsinternal
The options document of a password hash: the settings stored with each hash so it can be rebuilt and verified later.
passkeys::cborinternal
The CBOR decoder for passkey data: attestation objects, authenticator data and public keys, decoded into `Value`s.
passkeys::ceremonyinternal
Passkey registration and sign-in ceremonies: the options sent to the browser, the state kept in between, and the verification of what comes back.
passkeys::coseinternal
Passkey public keys in COSE form (RFC 9052/9053), and the signature algorithms ceremonies accept: ES256 and RS256.
passkeys1 items
WebAuthn passkeys for one relying party: registration and sign-in ceremonies with discoverable credentials, required user verification and no attestation.
passkeys::origininternal
The web origins allowed to run passkey ceremonies for a relying party.
passkeys::tagsinternal
The CBOR tags the passkey decoder knows: the checks each makes on its content and what it decodes to. Unknown tags decode to their content.
proofs::codeinternal
Numeric one-time codes, such as those sent by email or SMS.
proofs1 items
Secrets a user proves they know: passwords, one-time codes, tokens and passphrases, each generated and stored through a `Hash`.
proofs::passwordinternal
User passwords: a registry of named hashes, the one in use, and random password generation.
proofs::phraseinternal
Two-word passphrases that are easy to read out and type.
proofs::tokeninternal
Random hex tokens, such as those in magic links and recovery emails.
storeinternal
Session data carried between requests in a cookie or header.

API#

What utopia_auth exports at its root.