laravel-two-factor-rust 0.3.0

Laravel Two Factor for Rust: authenticator app codes, QR codes and recovery codes for Laravel for Rust
Documentation

Laravel Two Factor for Rust

crates.io docs.rs

Laravel Two Factor for Rust adds two-factor authentication with codes from an authenticator app to a Laravel for Rust app. Codes follow RFC 6238, so they work with Google Authenticator, 1Password, Authy and any app that scans a QR code.

Try it live on mischa.sigtermans.me.

Installation

cargo add laravel-two-factor-rust

The crate is imported as laravel_two_factor. Register its service provider:

use laravel::Application;
use laravel_two_factor::TwoFactorServiceProvider;

Application::configure().with_providers(|providers| {
    providers.add(TwoFactorServiceProvider);
});

Setup

Add three columns to users:

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .alter("users", |table| {
            table.text("two_factor_secret").nullable();
            table.text("two_factor_recovery_codes").nullable();
            table.timestamp("two_factor_confirmed_at").nullable();
        })
        .await
}

Keep the secret and the recovery codes encrypted, and out of responses:

use laravel::crypt::Encrypted;
use laravel::model::model;
use laravel::time::Timestamp;

#[model]
pub struct User {
    pub id: i64,
    pub email: String,
    #[serde(skip)]
    pub two_factor_secret: Option<Encrypted<String>>,
    #[serde(skip)]
    pub two_factor_recovery_codes: Option<Encrypted<Vec<String>>>,
    pub two_factor_confirmed_at: Option<Timestamp>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

Enabling

Take a TwoFactor as a handler argument. Give the user a pending secret and show it as a QR code. A user who already confirmed two-factor turns it off first, so a secret they never scanned can't replace theirs:

# use laravel::crypt::Encrypted; use laravel::model::model; use laravel::time::Timestamp;
# #[model] pub struct User { pub id: i64, pub email: String, #[serde(skip)] pub two_factor_secret: Option<Encrypted<String>>, #[serde(skip)] pub two_factor_recovery_codes: Option<Encrypted<Vec<String>>>, pub two_factor_confirmed_at: Option<Timestamp>, pub created_at: Timestamp, pub updated_at: Timestamp }
use laravel::db;
use laravel::model::update;
use laravel_two_factor::TwoFactor;

async fn enable(two_factor: TwoFactor, user_id: i64) -> laravel::Result<String> {
    db::transaction(async |_| {
        let mut user = User::query().filter(User::id.eq(user_id)).lock_for_update().first_or_fail().await?;
        laravel::abort_if(user.two_factor_confirmed_at.is_some(), 409)?;

        let secret = two_factor.generate_secret()?;
        let svg = two_factor.qr_code_svg(&secret, &user.email)?;
        update!(user { two_factor_secret: secret.to_base32(), two_factor_recovery_codes: None }).await?;

        Ok(svg)
    })
    .await
}

Two-factor turns on once the user types the code their app shows. Show the recovery codes once, after the commit:

# use laravel::crypt::Encrypted; use laravel::model::model; use laravel::time::Timestamp;
# #[model] pub struct User { pub id: i64, pub email: String, #[serde(skip)] pub two_factor_secret: Option<Encrypted<String>>, #[serde(skip)] pub two_factor_recovery_codes: Option<Encrypted<Vec<String>>>, pub two_factor_confirmed_at: Option<Timestamp>, pub created_at: Timestamp, pub updated_at: Timestamp }
use laravel::db;
use laravel::model::update;
use laravel_two_factor::{RecoveryCodes, Secret, TwoFactor};

async fn confirm(two_factor: TwoFactor, user_id: i64, code: String) -> laravel::Result<Option<Vec<String>>> {
    two_factor.attempt(&user_id.to_string()).await??;

    db::transaction(async |_| {
        let mut user = User::query().filter(User::id.eq(user_id)).lock_for_update().first_or_fail().await?;
        let (Some(stored), None) = (&user.two_factor_secret, &user.two_factor_confirmed_at) else {
            return Ok(None);
        };
        let secret: Secret = stored.parse()?;

        if !two_factor.verify_once(&secret, &code, &user_id.to_string()).await? {
            return Ok(None);
        }

        let recovery_codes = RecoveryCodes::generate(8);
        update!(user { two_factor_confirmed_at: laravel::now(), two_factor_recovery_codes: recovery_codes.clone() })
            .await?;

        Ok(Some(recovery_codes))
    })
    .await
}

Logging in

Limit the tries, lock the user's row so the secret you check is the current one, check the code with verify_once, and log the user in only after the transaction commits:

# use laravel::crypt::Encrypted; use laravel::model::model; use laravel::time::Timestamp;
# #[model] pub struct User { pub id: i64, pub email: String, #[serde(skip)] pub two_factor_secret: Option<Encrypted<String>>, #[serde(skip)] pub two_factor_recovery_codes: Option<Encrypted<Vec<String>>>, pub two_factor_confirmed_at: Option<Timestamp>, pub created_at: Timestamp, pub updated_at: Timestamp }
use laravel::db;
use laravel_two_factor::{Secret, TwoFactor};

async fn challenge(two_factor: TwoFactor, user_id: i64, code: String) -> laravel::Result<bool> {
    two_factor.attempt(&user_id.to_string()).await??;

    let passed = db::transaction(async |_| {
        let user = User::query().filter(User::id.eq(user_id)).lock_for_update().first_or_fail().await?;
        let (Some(stored), Some(_)) = (&user.two_factor_secret, &user.two_factor_confirmed_at) else {
            return Ok(false);
        };
        let secret: Secret = stored.parse()?;

        two_factor.verify_once(&secret, &code, &user_id.to_string()).await
    })
    .await?;

    // Committed: log the user in only now.
    Ok(passed)
}

Each code passes once per user. Spaces and hyphens in it are ignored.

Recovery codes

Each recovery code logs in once, and a used one is replaced, so the user keeps eight. Redeem under the same rate limit and row lock:

# use laravel::crypt::Encrypted; use laravel::model::model; use laravel::time::Timestamp;
# #[model] pub struct User { pub id: i64, pub email: String, #[serde(skip)] pub two_factor_secret: Option<Encrypted<String>>, #[serde(skip)] pub two_factor_recovery_codes: Option<Encrypted<Vec<String>>>, pub two_factor_confirmed_at: Option<Timestamp>, pub created_at: Timestamp, pub updated_at: Timestamp }
use laravel::db;
use laravel::model::update;
use laravel_two_factor::{RecoveryCodes, TwoFactor};

async fn recover(two_factor: TwoFactor, user_id: i64, code: String) -> laravel::Result<bool> {
    two_factor.attempt(&user_id.to_string()).await??;

    let redeemed = db::transaction(async |_| {
        let mut user = User::query().filter(User::id.eq(user_id)).lock_for_update().first_or_fail().await?;
        let (Some(stored), Some(_)) = (&user.two_factor_recovery_codes, &user.two_factor_confirmed_at) else {
            return Ok(false);
        };
        let mut codes = stored.to_vec();

        if !RecoveryCodes::redeem(&mut codes, &code) {
            return Ok(false);
        }

        update!(user { two_factor_recovery_codes: codes }).await?;

        Ok(true)
    })
    .await?;

    // Committed: log the user in only now.
    Ok(redeemed)
}

Configuration

Variable Default Means
TWO_FACTOR_ISSUER APP_NAME The name the app shows above the code, without a :
TWO_FACTOR_DIGITS 6 Digits per code: 6, 7 or 8
TWO_FACTOR_PERIOD 30 Seconds per code, up to 86400
TWO_FACTOR_WINDOW 1 Periods before and after the current one that also pass, up to 10
TWO_FACTOR_ALGORITHM SHA1 SHA1, SHA256 or SHA512
TWO_FACTOR_SECRET_BYTES 20 Bytes in a new secret, at least 16
TWO_FACTOR_CACHE_STORE CACHE_STORE The cache store verify_once keeps its marks in

The application won't start with a value no authenticator app can show. Google Authenticator ignores the algorithm, digits and period, so keep the defaults unless every user's app supports the change.

Production notes

  • With more than one process, use a shared cache store such as database or redis, and keep the servers' clocks in sync.
  • discard and failover cache stores are refused, for CACHE_STORE and TWO_FACTOR_CACHE_STORE both.
  • attempt gives each user one bucket of five tries, then one more every 12 seconds, shared by confirming, logging in and recovering.
  • With the database cache store, a code's check is final only once its transaction commits, so log in after the commit.
  • Secrets that Fortify or google2fa stored, 16 base32 characters, keep working.
  • Upgrading from 0.1.0: stop the old workers and wait period x (2 x window + 1) seconds, 90 at the defaults, before starting the new ones.

License

MIT