Previewkernable is not released yet: these docs describe work in progress, and things may change before 1.0.Not released yet.Request early access →
Skip to content

Passwords and other secrets ​

Use this page when a command carries a value that must never be stored: a password, a one-time code, a token. Mark the field secret: the handler sees it in clear, the log never does, and the kernel deletes it as soon as the command is done.

Set it up ​

  1. Turn the vault on: start the kernel with --vault-key (kernable start --dev does). Secrets are kept in the vault while their command runs; without a vault, the kernel refuses commands with secret fields (FAILED_PRECONDITION).
  2. Mark the field secret on the command, as the shop does for SetPassword and SignIn (highlighted below). Only top-level fields of commands can be secret.
  3. Give the client the domain, so it seals the field before signing: new Kernable().use(shopDomain), Python Kernable().use(shop_domain), Rust .with_domain(&shop_domain). A client without it sends the password in clear, and it is stored in the command log for good. kernable submit cannot seal fields: never use it for such commands.
  4. Store a hash, not the value, in the handler (see the rules below). The example stores an scrypt hash in PasswordSet, marked personal, so it is erased with the customer.
ts
// Personal data goes to the kernel's vault; the signed log keeps references only.
shopDomain.command("Register").personal(["email", "name"], (_d, id) => id);
shopDomain.event("CustomerRegistered", 1).personal(["email", "name"], (_d, id) => id);
shopDomain.command("Confirm").personal(["email"], (d: { customerId: string }) => d.customerId);
shopDomain.event("OrderConfirmed", 1).personal(["email"], (d: { customerId: string }) => d.customerId);
// Passwords are secrets: the handler sees them once; the vault deletes them when it is done.
shopDomain.command("SetPassword").secret(["password"]);
shopDomain.command("SignIn").secret(["password"]);
shopDomain.event("PasswordSet", 1).personal(["hash", "salt"], (_d, id) => id);
// Erasing a customer deletes their personal data everywhere, in every stream.
shopDomain.event("CustomerErased", 1).erases((_d, id) => id);

const hash = (password: string, salt: string) => scryptSync(password, salt, 32).toString("hex");

customerAggregate
  .apply("PasswordSet", (s, data: { hash: string; salt: string }) => { s.passwordHash = data.hash; s.salt = data.salt; })
  .apply("CustomerErased", (s) => { delete s.passwordHash; delete s.salt; s.registered = false; })
  .command("SetPassword", (s, data: { password: string }, _cmd, ctx) => {
    if (!s.registered) throw new Rejected("No such customer", "not_found");
    if ((data.password ?? "").length < 8) throw new Rejected("At least 8 characters", "invalid");
    const salt = ctx.id(); // deterministic: the command may run again
    return [{ type: "PasswordSet", data: { hash: hash(data.password, salt), salt } }];
  })
  .command("SignIn", (s, data: { password: string }) => {
    if (!s.passwordHash || hash(data.password ?? "", s.salt!) !== s.passwordHash) throw new Rejected("Wrong customer or password", "denied");
    return [{ type: "SignedIn" }];
  })
  .command("Erase", (s) => {
    if (!s.registered) throw new Rejected("No such customer", "not_found");
    return [{ type: "CustomerErased" }];
  });
py
# Personal data goes to the kernel's vault; the signed log keeps references only.
shop_domain.command("Register").personal(["email", "name"], lambda d, customer_id: customer_id)
shop_domain.event("CustomerRegistered", 1).personal(["email", "name"], lambda d, customer_id: customer_id)
shop_domain.command("Confirm").personal(["email"], lambda d: d["customerId"])
shop_domain.event("OrderConfirmed", 1).personal(["email"], lambda d: d["customerId"])
# Passwords are secrets: the handler sees them once; the vault deletes them when it is done.
shop_domain.command("SetPassword").secret(["password"])
shop_domain.command("SignIn").secret(["password"])
shop_domain.event("PasswordSet", 1).personal(["hash", "salt"], lambda d, customer_id: customer_id)
# Erasing a customer deletes their personal data everywhere, in every stream.
shop_domain.event("CustomerErased", 1).erases(lambda d, customer_id: customer_id)


def password_hash(password: str, salt: str) -> str:
    return hashlib.scrypt(password.encode(), salt=salt.encode(), n=2**14, r=8, p=1, dklen=32).hex()


@customer_aggregate.apply("PasswordSet")
def _(state, data):
    state["password_hash"] = data["hash"]
    state["salt"] = data["salt"]


@customer_aggregate.apply("CustomerErased")
def _(state, data):
    state.pop("password_hash", None)
    state.pop("salt", None)
    state["registered"] = False


@customer_aggregate.command("SetPassword")
def _(state, data, cmd, ctx):
    if not state["registered"]:
        raise Rejected("No such customer", "not_found")
    if len(data.get("password") or "") < 8:
        raise Rejected("At least 8 characters", "invalid")
    salt = ctx.id()  # deterministic: the command may run again
    return [{"type": "PasswordSet", "data": {"hash": password_hash(data["password"], salt), "salt": salt}}]


@customer_aggregate.command("SignIn")
def _(state, data):
    if "password_hash" not in state or password_hash(data.get("password") or "", state["salt"]) != state["password_hash"]:
        raise Rejected("Wrong customer or password", "denied")
    return [{"type": "SignedIn"}]


@customer_aggregate.command("Erase")
def _(state, data):
    if not state["registered"]:
        raise Rejected("No such customer", "not_found")
    return [{"type": "CustomerErased"}]
rs
#[derive(Deserialize)]
struct Password {
    password: Option<String>,
}

#[derive(Serialize, Deserialize)]
struct PasswordSet {
    hash: String,
    salt: String,
}

fn vault(shop_domain: &Domain, customer_aggregate: &Aggregate<Customer>) {
    let aggregate = |_: &Value, id: &str| id.to_owned();
    let customer_id = |d: &Value, _: &str| d["customerId"].as_str().unwrap_or_default().to_owned();
    // Personal data goes to the kernel's vault; the signed log keeps references only.
    shop_domain
        .command("Register")
        .personal(&["email", "name"], aggregate);
    shop_domain
        .event("CustomerRegistered", 1)
        .personal(&["email", "name"], aggregate);
    shop_domain
        .command("Confirm")
        .personal(&["email"], customer_id);
    shop_domain
        .event("OrderConfirmed", 1)
        .personal(&["email"], customer_id);
    // Passwords are secrets: the handler sees them once; the vault deletes them when it is done.
    shop_domain.command("SetPassword").secret(&["password"]);
    shop_domain.command("SignIn").secret(&["password"]);
    shop_domain
        .event("PasswordSet", 1)
        .personal(&["hash", "salt"], aggregate);
    // Erasing a customer deletes their personal data everywhere, in every stream.
    shop_domain.event("CustomerErased", 1).erases(aggregate);

    customer_aggregate.apply("PasswordSet", |s, data: PasswordSet, _evt, _ctx| {
        s.password_hash = Some(data.hash);
        s.salt = Some(data.salt);
    });
    customer_aggregate.apply("CustomerErased", |s, _: Value, _evt, _ctx| {
        *s = Customer::default()
    });
    customer_aggregate.command("SetPassword", |s, data: Password, _cmd, ctx| {
        if !s.registered {
            return Err(Rejected::new("No such customer").code("not_found"));
        }
        let password = data.password.unwrap_or_default();
        if password.chars().count() < 8 {
            return Err(Rejected::new("At least 8 characters").code("invalid"));
        }
        let salt = ctx.id(); // deterministic: the command may run again
        Ok(vec![NewEvent::new(
            "PasswordSet",
            PasswordSet {
                hash: hash(&password, &salt),
                salt,
            },
        )])
    });
    customer_aggregate.command("SignIn", |s, data: Password, _cmd, _ctx| {
        let password = data.password.unwrap_or_default();
        match (&s.password_hash, &s.salt) {
            (Some(stored), Some(salt)) if hash(&password, salt) == *stored => {
                Ok(vec![NewEvent::new("SignedIn", ())])
            }
            _ => Err(Rejected::new("Wrong customer or password").code("denied")),
        }
    });
    customer_aggregate.command("Erase", |s, _: Value, _cmd, _ctx| {
        if !s.registered {
            return Err(Rejected::new("No such customer").code("not_found"));
        }
        Ok(vec![NewEvent::new("CustomerErased", ())])
    });
}

/// scrypt with the parameters of the TypeScript and Python shops, so their hashes match.
fn hash(password: &str, salt: &str) -> String {
    let params = scrypt::Params::new(14, 8, 1, 32).expect("valid scrypt parameters");
    let mut out = [0u8; 32];
    scrypt::scrypt(password.as_bytes(), salt.as_bytes(), &params, &mut out).expect("32 bytes fit");
    out.iter().map(|b| format!("{b:02x}")).collect()
}

What happens to the value ​

  • The client moves the field to the vault before signing the command; the stored command keeps a reference, {"$vault": "…"}. The reference is part of the command's signature: nobody can swap the value without breaking it.
  • The worker gets the value in clear for as long as the command runs, also when it is delivered again after a crash. So do middlewares granted vault_read for the command.
  • The vault deletes it as soon as the command completed, committed or rejected. A kernel that restarts deletes those of commands that completed meanwhile. A command that waits in the queue keeps its secret until it completes.
  • A middleware that rejects the command before it is queued leaves nothing behind: the value never reaches the vault.

Check it in the stores: the command holds the reference only, and no secret is left once no command runs.

sh
sqlite3 kernable.db "SELECT payload FROM commands WHERE command_type = 'SetPassword'"   # {"password":{"$vault":"…"}}
sqlite3 vault.db "SELECT count(*) FROM vault WHERE secret = 1"                         # 0

Rules for handlers ​

  • Never put a secret into an event, a log line or an error message. Store a hash, salted and slow (scrypt, Argon2), and mark it personal so it is erased with the person (Handle an erasure request).
  • Derive the salt with ctx.id(). Handlers must decide the same way when a command runs again; a random salt would differ.
  • Compare in a command, like SignIn: the stored hash stays in the aggregate, and the answer is the outcome (committed, or rejected with denied). Use the same message for an unknown person and a wrong password.
  • One-time codes: store a hash with an expiry in an event, and send the code itself as a secret in the command that uses it.

How the vault works: Personal data: the vault.