Files
iam/internal/oidc/signup.go
wbin90620 9d4d6b3d0d A GitHub sign-up is named after its GitHub login when the name is free
A federated account was always named from its email's local part, so a
person who signed up with GitHub as Darkhorse7stars became "wbin90620" here,
a name they never chose. GitHub keeps a handle of its own: the login, which
the person chose and GitHub holds unique.

- githubExchange carries the login on the federated identity (handle).
- provisionFederatedUser names the account through federatedName: the
  handle, lowercased by schema.Username, when it is a usable username and
  nobody here holds it (nameTaken, as allocateName asks); otherwise
  allocateName's address-derived name and numbered walk, unchanged. A held
  handle is not numbered, because "octocat2" reads as another GitHub user.
- Google keeps no handle, so a Google sign-up is named as before; a display
  name ("Grace Hopper") is still never a username.

TestProvisionFederatedUser_TakesTheProvidersHandleWhenFree covers a free
login, a held one, an empty one and Google.
2026-10-20 12:04:26 -04:00

717 lines
31 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package oidc
import (
"context"
"errors"
"fmt"
"net/mail"
"regexp"
"strconv"
"strings"
"unicode/utf8"
policy "github.com/hanzoai/authz"
"github.com/hanzoai/orm"
"github.com/zap-proto/zip"
"github.com/hanzoai/iam/internal/httpx"
"github.com/hanzoai/iam/internal/otp"
"github.com/hanzoai/iam/internal/users"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/pkg/store"
)
// The native signup endpoint: POST /v1/iam/signup. The @hanzo/iam SDK + the
// hanzo.id portal post the sign-up form here to create a new account. It mirrors
// the v1 the legacy surface Signup contract (controllers/account.go): the casibase
// {status,msg,data} envelope, resolve-app → enforce-policy → create-user, with
// the password hashed (never stored plaintext) and the created row returned
// REDACTED.
//
// A signup carries the code /v1/iam/verification-codes sent to its address. A
// right code records the address proven on the account it creates; a wrong one
// creates nothing. Where the application cannot send a code, a signup brings none
// and records an address nobody has proven.
// PathSignup is the canonical native signup endpoint.
const PathSignup = "/v1/iam/signup"
// signupForm is the sign-up request the SDK/portal posts — the signup-relevant
// subset of v1's form.AuthForm.
type signupForm struct {
Application string `json:"application"`
ClientId string `json:"clientId"`
Organization string `json:"organization"`
// Username is OPTIONAL. A caller that names one is asking for that exact name
// and gets it or a refusal; a caller that names none — the signup screen, which
// has no such field — gets one minted from the address. Either way the value
// stored is IAM's to decide, never the spelling that arrived.
Username string `json:"username"`
Password string `json:"password"`
Name string `json:"name"` // display name
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email string `json:"email"`
// Code is the one-time code sent to Email. It proves the address before any
// account holds it, which is the only moment the person proving it is certainly
// the person choosing the password.
Code string `json:"code"`
Phone string `json:"phone"`
CountryCode string `json:"countryCode"`
Affiliation string `json:"affiliation"`
// Invitation is the code of an invitation the named org's admin wrote. It is
// the one way a signup joins an org that is already standing (see invitation).
Invitation string `json:"invitationCode"`
// Training is the answer to the AI-training question the signup screen asks,
// recorded with the account rather than left for a later prompt. Absent means
// unanswered — which reads as refusal everywhere — so a client that does not
// ask cannot accidentally grant, and the screen is what turns silence into an
// explicit answer. A non-empty value that is not a known answer is refused
// outright rather than coerced.
Training string `json:"training"`
// Terms and AUP are the versions of the Terms of Service and the Acceptable
// Use Policy the person agreed to on the signup screen, recorded with the
// account as a code sign-up records them. Both, or neither.
Terms string `json:"terms"`
AUP string `json:"aup"`
}
// signupHandler creates an account from the sign-up form and applies the
// application's own sign-up rules — whether self-service registration is open at
// all, and which fields it requires.
//
// The password is hashed before it is stored and is never returned.
func signupHandler(db orm.DB) zip.Handler {
return func(c *zip.Ctx) error {
var f signupForm
if err := c.Bind(&f); err != nil {
return httpx.Err(c, "invalid request body")
}
ctx := c.Context()
f.Organization = strings.TrimSpace(f.Organization)
f.Username = strings.TrimSpace(f.Username)
if f.Organization == "" || f.Password == "" {
return httpx.Err(c, "organization and password are required")
}
// Resolve the training answer before anything is created, so an account is
// never persisted alongside an answer this version cannot interpret.
consent := schema.Consent{Insights: true, Training: schema.Answer(f.Training)}
if !consent.Training.Valid() {
return httpx.Err(c, "training must be one of: \"\", granted, refused")
}
var accepted *schema.Terms
if f.Terms != "" || f.AUP != "" {
if !termsVersion.MatchString(f.Terms) || !termsVersion.MatchString(f.AUP) {
return httpx.Err(c, "the terms and the acceptable use policy must be accepted")
}
accepted = &schema.Terms{
Terms: f.Terms,
AUP: f.AUP,
Time: nowFunc().UTC().Format("2006-01-02T15:04:05Z07:00"),
Method: methodPassword,
IP: httpx.ClientIP(c),
}
}
// Resolve the application (by clientId when present, else by name under the
// admin owner — the iam storage convention), then enforce its policy.
app, err := ResolveApp(ctx, db, f.ClientId, f.Application)
if err != nil {
return httpx.Err(c, err.Error())
}
if app == nil {
return httpx.Err(c, "the application: "+f.Application+" does not exist")
}
if !app.EnableSignUp {
return httpx.Err(c, "the application does not allow to sign up new account")
}
if !app.EnablePassword {
return httpx.Err(c, "the application does not allow password sign-up")
}
// A self-service signup may NEVER resolve to a reserved system org
// (admin/built-in/app). A user created under "admin" is a SuperAdmin — authz
// derives Super from owner == "admin" — so this is THE privilege escalation to
// refuse, and it must hold INDEPENDENT of the app: an admin-org app, a shared
// app, or an org-choice app would each otherwise admit `organization=admin`
// through the tenant gate below and mint a SuperAdmin. This is the same
// policy.IsReservedOrg refusal onboarding and federated provisioning apply — the
// ONE reserved-org predicate, so signup can never drift from them. The message
// is byte-identical to the tenant refuse below, so a prober cannot distinguish
// "reserved org" from "wrong tenant" (no existence/authority oracle).
if policy.IsReservedOrg(f.Organization) {
return httpx.Err(c, "the user is not permitted to sign up to this application")
}
// Tenant isolation. A signup lands in an org it founds, in the application's
// own org where the application serves no other (Registers), or in an org
// whose admin invited it — never in an org it merely names.
//
// A shared application used to admit any org it was handed: shared reads as
// "serves many tenants", which is true of SIGN-IN, where the person already
// belongs to one. At signup nobody belongs anywhere yet, so an unauthenticated
// POST naming any standing org — a brand, a customer — was made a member of it.
// Sign-in keeps ServesAnyOrg; signup no longer reads it.
//
// A code that was brought and redeems nothing is refused rather than read as
// no code: the person asked to join an org, and founding one instead, or
// filing them in the application's, puts them where they did not ask to be.
// Every refusal here is the same sentence as the reserved-org one above, so a
// prober learns neither which orgs stand nor which codes exist.
invite, err := invitation(ctx, db, app, &f)
if err != nil {
return httpx.Err(c, err.Error())
}
if invite == nil && f.Invitation != "" {
recordInviteGuess(ctx, db, f.Organization)
}
if invite == nil && (f.Invitation != "" || !Registers(app, f.Organization)) {
return httpx.Err(c, "the user is not permitted to sign up to this application")
}
if invite != nil && f.Username == "" {
f.Username = invite.Username
}
org, err := store.GetOrganizationByName(ctx, db, f.Organization)
if err != nil {
return httpx.Err(c, err.Error())
}
if org == nil {
// Signup does not mint organizations. It used to, opt-in per app, and that
// made an UNAUTHENTICATED request able to add a row to the tenant registry
// — a probe could leave an org behind simply by posting a signup.
//
// Nothing asked for it either. The screen posts the app's own org and asks
// for the organization in ONBOARDING, and POST /v1/iam/onboard is a better
// answer to the same question in every respect: it authenticates the caller,
// acts only on the caller, is idempotent, and provisions the org's metered
// credential in the same atomic step — so it lands a person somewhere they
// can actually work, where this landed them in an org with no billing
// account. Two ways to create an org, one of them needing no identity and
// producing the worse result, is one way too many.
return httpx.Err(c, "the organization: "+f.Organization+" does not exist")
}
// Password policy (v1 org.PasswordOptions complexity) BEFORE either uniqueness
// check, so no answer about who already has an account is free: a probe has to
// bring a password this org would actually accept to learn anything. It reads
// in the right order too — the rules that are about the request alone come
// first, and only then does anything look at the directory.
if msg := passwordPolicyError(org.PasswordOptions, f.Password); msg != "" {
return httpx.Err(c, msg)
}
email := store.NormalizeEmail(f.Email)
if email != "" {
if !isEmailValid(email) {
return httpx.Err(c, "email is invalid")
}
// An address that already names an account is taken, and an address that
// names TWO is taken twice over — ErrEmailAmbiguous is a uniqueness answer
// here, not a lookup failure, so it lands on the uniqueness message rather
// than reporting the store's broken invariant to a stranger.
switch existing, err := store.GetUserByEmail(ctx, db, f.Organization, email); {
case err == store.ErrEmailAmbiguous, existing != nil:
return httpx.Err(c, "email already exists")
case err != nil:
return httpx.Err(c, err.Error())
}
// And among the accounts registered in the application's org, which are no
// longer in the org just searched. Founding empties the org of exactly the
// accounts this is checking against, so without this the address reads as
// free the moment its owner moves out — the second person registers it, or
// the same person registers again at another of the org's applications, and
// then NEITHER account can sign in, because one address across two of one
// org's registrations names nobody.
switch existing, err := store.GetSignupByEmail(ctx, db, app.Organization, email); {
case err == store.ErrEmailAmbiguous, existing != nil:
return httpx.Err(c, "email already exists")
case err != nil:
return httpx.Err(c, err.Error())
}
// Where a code can reach the address, the address is proven or not taken.
// An account holding it unproven is one its owner can never have: they
// cannot register it again, a social sign-in will not adopt it, and the
// password is someone else's.
//
// Asked after the address is known to be free, so the first submit, which
// carries no code, already answers "email already exists": the person is
// sent to sign-in or recovery before a code goes to an address that has an
// account. The answer is the one a wrong code has always drawn, since the
// code is spent last.
//
// An invitation pinned to this address asks for the same proof whatever
// the application offers: the pin says who may take the seat, and an
// account that never proved the address would hold it unproven.
if f.Code == "" && (sendsCodes(app) || (invite != nil && invite.Email != "")) {
return httpx.Err(c, "the code sent to the email address is required")
}
}
// The username. A caller that NAMES one gets exactly that name or a refusal —
// provisioning a known name is a real use, and silently substituting another
// would hand back a different principal than the one asked for. A caller that
// names none gets one minted from the address, through the SAME derivation
// federated signup walks (allocateName), so the two ways an account enters this
// store agree on what an address is worth as a name.
//
// The signup screen has no username field, and the portal used to fill the gap
// in the browser with `email.split('@')[0]`. That guess cost two dead ends: a
// plus-address — `[email protected]`, one of the commonest real address
// forms — was refused outright, because "+" is not in the username charset and
// nothing on that path reduced the local part to the charset; and the SECOND
// person whose local part collided was refused "username already exists", about
// a field they were never shown and could not change. Both are gone the moment
// the derivation moves to the side that can see the directory: schema.Handle
// drops the subaddress marker, and the walk that federation has always done
// hands out `alice2`.
if f.Username == "" {
if email == "" {
return httpx.Err(c, "an email address or a username is required")
}
name, err := allocateName(ctx, db, f.Organization, app.Organization, email, "")
if err != nil {
return httpx.Err(c, err.Error())
}
f.Username = name
} else {
// THE username rule (schema.Username), applied at the endpoint so the caller gets
// the reason rather than a bare conflict — and so the uniqueness check runs
// against the value that will actually be stored. Probing uniqueness with the
// raw spelling while storing the normalized one is how "Alice" gets admitted
// next to an existing "alice".
name, err := schema.Username(f.Username)
if err != nil {
return httpx.Err(c, err.Error())
}
f.Username = name
if taken, err := nameTaken(ctx, db, f.Organization, app.Organization, name); err != nil {
return httpx.Err(c, err.Error())
} else if taken {
return httpx.Err(c, "username already exists")
}
}
// The address is proven here or not at all: the code was sent to it before any
// account held it, so whoever holds the code holds the address, and they are
// the one choosing this password. It is spent last, after every refusal that is
// about the request, so a person who mistyped their password does not also lose
// the code; a wrong code counts against the code like any other guess.
proven := false
if f.Code != "" {
if email == "" {
return httpx.Err(c, "a code proves an email address; none was given")
}
ok, err := otp.Prove(ctx, db, app.Organization, email, f.Code, nowFunc())
if err != nil {
return httpx.Err(c, err.Error())
}
if !ok {
return httpx.Err(c, "the code is incorrect or has expired")
}
proven = true
}
// The invitation's seat is spent after the address code, so a mistyped code
// costs the org no seat, and before the account exists, so a seat is never
// taken twice by two signups racing for the last one.
if invite != nil {
spent, err := redeem(ctx, db, invite, app, &f)
if err != nil {
return httpx.Err(c, err.Error())
}
if !spent {
return httpx.Err(c, "the user is not permitted to sign up to this application")
}
}
// Create through the ONE canonical user path (users.Create): argon2id-hash the
// password once, persist, return the REDACTED row (no plaintext, no digest ever
// stored or returned). PasswordType is stamped "argon2id" — exactly what
// internal/cred verifies for a new iam row.
created, err := users.New(db).Create(ctx, &users.CreateInput{
// The class and the registering application are stated here, beside the
// create, rather than inside the user body — a signup makes a PERSON through
// THIS application, and only this code may say so.
Type: "normal-user",
Application: app.Name,
EmailVerified: proven,
User: schema.User{
Owner: f.Organization,
Name: f.Username,
DisplayName: displayName(f),
FirstName: f.FirstName,
LastName: f.LastName,
Email: email,
Phone: store.NormalizePhone(f.Phone),
CountryCode: f.CountryCode,
Affiliation: f.Affiliation,
Avatar: org.DefaultAvatar,
RegisterType: "Application Signup",
RegisterSource: f.Organization + "/" + app.Name,
Invitation: invitationName(invite),
},
Password: f.Password,
// The answer the screen collected, recorded WITH the account. A new
// user therefore starts with an explicit answer instead of silence, and
// silence — for any account created by a path that does not ask — still
// reads as refusal. It rides the typed seam rather than a properties
// blob assembled here, because that blob is exactly what Create drops:
// this is the one caller entitled to state an answer, and being
// in-process is what distinguishes it from a request that claims to be.
Consent: &consent,
Terms: accepted,
})
if err != nil {
return httpx.Err(c, err.Error())
}
// The account is REGISTERED in the application's org — that is what every
// check above just decided — and at a founding application it WORKS in an org
// of its own, which this founds and moves it into.
//
// The two are different things. The application's org is where a username is
// unique and where the sign-in screen looks; the tenant is what holds
// credentials, connections and spend. An application open to strangers must
// keep them apart, or everyone it registers is a member of whichever tenant
// that application happens to belong to.
//
// Signup still does not mint an org the CALLER names — the refusal above is
// untouched, and it is what stopped an unauthenticated POST adding a row to
// the tenant registry. This slug is DERIVED, from an account this request has
// just created, so nothing about it is the caller's to choose.
//
// It is the same converge onboarding drives, not a second one: org + founder
// moved in as its admin + its owner membership + the org's metered credential,
// idempotent and resumable. So a person who signs up and a person who onboards
// arrive in the same state, and there is one place where founding an org is
// written down.
//
// An invited account founds nothing: it joins the org whose admin asked it to.
if invite == nil && app.OrgChoiceMode == orgChoiceCreate {
org, err := charter(ctx, db, created)
if err != nil {
return httpx.Err(c, err.Error())
}
// The move re-keyed the row, so the response must name where the account
// actually is. Returning the pre-move owner tells the client to address an
// identity that no longer exists.
created.Owner = org
}
return httpx.Ok(c, created)
}
}
// charter founds the organization an account works in and moves the account into
// it, returning the org's name.
//
// The name is derived from the account, never taken from a request: a signup is
// unauthenticated, and a caller that could NAME the org would be writing a row of
// its choosing into the tenant registry.
func charter(ctx context.Context, db orm.DB, user *schema.User) (string, error) {
org, err := found(ctx, db, user)
if err == nil {
return org, nil
}
// The account was made for this founding. If it is still where it was made,
// it was never moved into an org of its own, and left there it would be a
// member of whichever tenant the application belongs to — so it goes.
if made, gerr := store.GetUserByName(ctx, db, user.Owner, user.Name); gerr == nil && made != nil {
if derr := store.DeleteUser(ctx, db, made); derr != nil {
return "", fmt.Errorf("%w (and the account it was for could not be removed: %v)", err, derr)
}
}
return "", err
}
// found derives the account's org name, founds it and moves the account in.
func found(ctx context.Context, db orm.DB, user *schema.User) (string, error) {
// personalOrgSlug caps its derivation at maxOrgSlug, and the walk appends to
// what it returns, so the base is trimmed to leave the suffix room. orgSlugFree
// refuses a slug over that bound, so an account whose address is merely long
// would otherwise walk past every candidate and be refused at the end of its
// signup, for a rule about a name it never chose.
base := personalOrgSlug(user.Name)
if room := maxOrgSlug - len(strconv.Itoa(nameAttempts)); len(base) > room {
base = base[:room]
}
slug, err := allocate(base, func(s string) (bool, error) { return orgSlugFree(ctx, db, s) })
if err != nil {
return "", err
}
out, err := provision(ctx, db, claim{
owner: user.Owner, name: user.Name,
slug: slug, display: user.Name, personal: true, move: true,
})
if err != nil {
return "", err
}
return out.org, nil
}
// Charter founds the org a new account works in when app founds one for each
// account it registers, and returns the account where it then lives; any other
// app leaves it where it was made. Every way an account is made — a password, a
// provider, a wallet — ends here, so a person arrives in the same place whichever
// way they came in.
//
// It re-reads the account rather than patching the row in hand: the converge moved
// it and made it its org's admin, and the caller mints this person's first token
// from what comes back.
func Charter(ctx context.Context, db orm.DB, app *schema.Application, user *schema.User) (*schema.User, error) {
if app.OrgChoiceMode != orgChoiceCreate {
return user, nil
}
org, err := charter(ctx, db, user)
if err != nil {
return nil, err
}
return store.GetUserByName(ctx, db, org, user.Name)
}
// orgChoiceCreate is the application's declaration that a signup FOUNDS the
// person's own organization: they are its sole member, and they join a team org
// — hanzo, lux, zoo or any customer's — separately, by membership. An
// application that declares anything else registers its accounts in its own org
// and leaves the tenant to onboarding.
//
// It is the mode the org picker already names, read where the founding happens.
// Application.ServesAnyOrg reads the same value for the tenant exemption, which
// this makes true rather than merely permitted: a founding app's accounts really
// do live in orgs that are not its own.
const orgChoiceCreate = "create"
// orgSlugFree reports whether slug may be founded as a new organization: long
// enough to be one, not a held name, not already standing, and not held by rows a
// removed org left behind — the same question provision asks.
//
// All three are reasons a slug is unavailable, so they are one predicate — a
// derivation that walked only past TAKEN names would hand provision a name it
// refuses, and the person's signup would fail on a rule they never saw.
func orgSlugFree(ctx context.Context, db orm.DB, slug string) (bool, error) {
if len(slug) < minOrgSlug || len(slug) > maxOrgSlug || policy.IsHeldOrg(slug) {
return false, nil
}
org, err := store.GetOrganizationByName(ctx, db, slug)
if err != nil || org != nil {
return false, err
}
held, err := store.OrgHeld(ctx, db, slug)
return !held, err
}
// nameTaken reports whether a new account in org may not take name: a user of org
// holds it, or an account an application of registrar registered holds it, in
// whatever org it now works. The second half is what keeps a username unique across
// the accounts one org registers — founding moves each of them out of the org this
// first half searches, and a name two of them hold signs neither in
// (store.SignupByName).
func nameTaken(ctx context.Context, db orm.DB, org, registrar, name string) (bool, error) {
if u, err := store.GetUserByName(ctx, db, org, name); err != nil || u != nil {
return u != nil, err
}
_, held, err := store.SignupByName(ctx, db, registrar, name)
return held > 0, err
}
// nameAttempts bounds the dedupe walk: the first free suffix wins, and a name
// that is still taken after this many tries means something is wrong with the
// derivation, not that the org is full.
const nameAttempts = 32
// allocate returns base, or the first numbered variant of it that free accepts —
// alice, alice2, alice3. A person gets the name they would have chosen and the
// suffix appears only when it has to.
//
// One walk, because a signup derives two names under the same rule (the username,
// and the slug of the org it founds) and they must not drift into disagreeing
// about what the second Alice is called. What "free" means belongs to the caller:
// a username is free when the org has nobody by it, a slug when no organization
// may be, is, or already stands under it.
func allocate(base string, free func(string) (bool, error)) (string, error) {
for attempt := 1; attempt <= nameAttempts; attempt++ {
candidate := base
if attempt > 1 {
candidate += strconv.Itoa(attempt)
}
ok, err := free(candidate)
if err != nil {
return "", err
}
if ok {
return candidate, nil
}
}
return "", errors.New("could not allocate a unique name")
}
// allocateName mints the username a NEW account gets in org, registered by an
// application of registrar: the handle its address yields, or the first free
// variant of it ([nameTaken]). It is the ONE derivation both
// ways into this store use — a password signup with no username of its own, and a
// federated signup whose provider keeps no free handle for the person
// ([federatedName]).
//
// What an address yields is schema.Handle's to decide, and only the ADDRESS may
// become an identity: an IdP profile says "Grace Hopper", which is not a username
// in any spelling and must never be turned into one. fallback is the value to
// derive from when the address yields nothing — the provider TYPE ("google") for a
// federated signup, which is the only other value on that path that is not a
// human's name. Empty when the caller has no such value.
//
// The walk is [allocate]'s: [email protected] becomes "alice", then "alice2",
// "alice3". That replaced a random 8-hex suffix on EVERY name ("z-3f9ab21c"),
// which made collisions impossible by making every name unrecognisable.
func allocateName(ctx context.Context, db orm.DB, org, registrar, email, fallback string) (string, error) {
base := schema.Handle(email)
if base == "" {
base, _ = schema.Username(fallback)
}
if base == "" {
base = "user"
}
return allocate(base, func(name string) (bool, error) {
taken, err := nameTaken(ctx, db, org, registrar, name)
return !taken, err
})
}
// federatedName mints the username a NEW federated account gets in org: the
// provider's handle for the person (GitHub's login) when the provider keeps one,
// it is a usable username, and nobody here holds it — the name they already go by
// — and otherwise what [allocateName] derives from the address, with its numbered
// walk. A handle that is taken is not numbered: "octocat2" would read as the
// GitHub user octocat2, who is someone else, so the address's name is used instead.
//
// Only a HANDLE qualifies, never a display name ("Grace Hopper"), and a provider
// with no handles (Google) gets the address's name as before.
func federatedName(ctx context.Context, db orm.DB, org string, id federatedIdentity, fallback string) (string, error) {
if handle, err := schema.Username(id.handle); err == nil {
taken, err := nameTaken(ctx, db, org, org, handle)
if err != nil {
return "", err
}
if !taken {
return handle, nil
}
}
return allocateName(ctx, db, org, org, id.email, fallback)
}
// displayName is the user's display name: the supplied name, a "First Last"
// composite, or the username as a last resort — v1's precedence.
func displayName(f signupForm) string {
if f.FirstName != "" || f.LastName != "" {
if n := strings.TrimSpace(f.FirstName + " " + f.LastName); n != "" {
return n
}
}
if f.Name != "" {
return f.Name
}
return f.Username
}
// Password-complexity option matchers — the v1 object/check_password_complexity.go
// option set, driven by the organization's PasswordOptions.
var (
pwReLower = regexp.MustCompile(`[a-z]`)
pwReUpper = regexp.MustCompile(`[A-Z]`)
pwReDigit = regexp.MustCompile(`\d`)
pwReSpecial = regexp.MustCompile("[!-/:-@[-`{-~]")
)
// pwFloorMinLength is the PLATFORM password floor: the minimum length every
// password must meet no matter what the organization declares. It is the same
// "AtLeast8" every seeded organization already carries (init_data.json), lifted
// out of configuration and into code so that it cannot be configured away — and
// so an organization that declares nothing is not thereby exempt.
const pwFloorMinLength = 8
// passwordPolicyError returns the first complexity rule the password violates,
// or "" when it passes: the platform floor first, then the organization's own
// options, which may only ever make the policy STRICTER.
//
// The floor exists because the option set alone is a policy an org can hold
// EMPTY. A self-serve org is created with no PasswordOptions,
// so "no options" — which used to mean "any non-empty password" — was reachable
// by an anonymous caller: a self-serve signup was accepted with the single byte
// "a", and that account then logged in. Enforcing the floor here rather than
// stamping defaults onto each new org keeps ONE source of truth: options are
// additive strictness on top of an invariant, not the invariant itself.
func passwordPolicyError(options []string, password string) string {
if password == "" {
return "password cannot be empty"
}
// Length is counted in RUNES, once, for the floor and for the org options
// alike — a byte count would let a handful of multi-byte characters satisfy
// an "8 characters" rule, and would let the floor and AtLeast8 disagree about
// what "8 characters" means.
n := utf8.RuneCountInString(password)
if n < pwFloorMinLength {
return "the password must have at least 8 characters"
}
// A password of one repeated rune ("aaaaaaaa") is the length floor's trivial
// evasion and cannot be a real user's choice, so refuse it outright. This is
// deliberately narrower than the NoRepeat option below, which refuses ANY two
// adjacent equal runes and would reject legitimate passwords.
if isSingleRepeatedRune(password) {
return "the password must not be a single repeated character"
}
for _, opt := range options {
switch opt {
case "AtLeast6":
if n < 6 {
return "the password must have at least 6 characters"
}
case "AtLeast8":
if n < 8 {
return "the password must have at least 8 characters"
}
case "Aa123":
if !pwReLower.MatchString(password) || !pwReUpper.MatchString(password) || !pwReDigit.MatchString(password) {
return "the password must contain at least one uppercase letter, one lowercase letter and one digit"
}
case "SpecialChar":
if !pwReSpecial.MatchString(password) {
return "the password must contain at least one special character"
}
case "NoRepeat":
for i := 0; i+1 < len(password); i++ {
if password[i] == password[i+1] {
return "the password must not contain any repeated characters"
}
}
}
}
return ""
}
// isSingleRepeatedRune reports whether s is one rune repeated — "a", "aaaaaaaa",
// "………". Used by the floor to refuse the length rule's trivial evasion.
func isSingleRepeatedRune(s string) bool {
first, size := utf8.DecodeRuneInString(s)
for _, r := range s[size:] {
if r != first {
return false
}
}
return true
}
// isEmailValid reports whether s parses as an email address — v1's
// util.IsEmailValid (net/mail.ParseAddress), the single email check shared by
// signup and send-verification-code.
func isEmailValid(s string) bool {
_, err := mail.ParseAddress(s)
return err == nil
}