Give the POS a real sign-in, and stop believing the store id on the wire
The POS surface was open. A till named its own outlet — `store_id` in a query or in an ingest batch — and was believed, so one number changed in Settings read another tenant's catalogue or posted bills into their books. There was no middleware in the codebase at all, and the `JWT_SECRET_KEY` in the config was read and never used. Products were never mis-scoped: `resolvePosStore` already derived the tenant from the location and the catalogue query already filtered on both. The tenant was never taken from the wire. What was missing was any check that the caller was entitled to the location they named. So the outlet now comes *out* of a sign-in rather than going *in* from the till. `POST /pos/login` authenticates against the same `app_users` rows the web console uses — one account store, so deactivating a leaver closes both doors — and answers with the outlets that account may reach, sealed in an HMAC-SHA256 token the terminal cannot edit. Two checks then guard everything else, in order: the token verifies, and the outlet named in the request belongs to the token's tenant. The second is the one that matters — a valid token is a licence to name *your* outlets, not any. Notes on the awkward parts: - The guard reads the outlet from the body as well as the query. The two routes that write carry `store_id` in a JSON batch and never in the URL, so a query-only check would have left exactly the dangerous call unguarded. - Three spellings of one thing survive — `store_id`, `locationid`, `location_id`. All three are read rather than normalised, because renaming them breaks terminals already in the field. - `POS_AUTH_REQUIRED` defaults to false. Tills are billing real customers against the open endpoints right now and enforcing at deploy would stop every one mid-trade. A token is still verified when sent, and a wrong-tenant token still refused; the flag only governs requests carrying none. - `POS_TOKEN_SECRET` has no baked-in fallback and fails loudly. A development secret in source is the same as no signature at all. - `configid` is inferred when the till does not send it, because a person at a counter has no way to know theirs. `authname` is not unique in this schema — live data has one address twice under one configid — so an ambiguous match is refused rather than resolved by LIMIT 1, which could bill into the wrong tenant's books. Verified against live data: 58 accounts across 34 tenants can open a till, an account pinned to a location resolves to it alone, a tenant-level account gets all six of its outlets, and a cross-tenant outlet request is refused. Passwords are still plaintext platform-wide. Flagged at the comparison site; fixing it is a migration touching every login path, not this endpoint. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
299
repositories/posAuthRepository.go
Normal file
299
repositories/posAuthRepository.go
Normal file
@@ -0,0 +1,299 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"nearle/models"
|
||||
)
|
||||
|
||||
// Sign-in for the POS terminal.
|
||||
//
|
||||
// Deliberately reads the same `app_users` rows the web console authenticates
|
||||
// against rather than introducing a terminal-specific credential table. A shop
|
||||
// manager who can sign into the back office should be able to open the till
|
||||
// with the same details, and one account store means deactivating a leaver
|
||||
// closes both doors at once instead of one and a half.
|
||||
//
|
||||
// Kept in its own file because the rest of posRepository is about moving bills
|
||||
// and stock, and mixing authorisation into that made the one thing nobody
|
||||
// should have to hunt for the hardest thing to find.
|
||||
|
||||
// posLoginRow is the credential check's raw answer.
|
||||
type posLoginRow struct {
|
||||
Userid int
|
||||
Password string
|
||||
Status string
|
||||
Roleid int
|
||||
Configid int
|
||||
Tenantid int
|
||||
Locationid int
|
||||
Firstname string
|
||||
Lastname string
|
||||
Email string
|
||||
}
|
||||
|
||||
// PosLogin authenticates a user and returns the session they are entitled to.
|
||||
//
|
||||
// The outlet is resolved here, from the user's own row and the tenant's list of
|
||||
// locations — never from anything the caller sent. That inversion is the whole
|
||||
// point of the endpoint.
|
||||
func (r *posRepository) PosLogin(req models.PosLoginRequest) (*models.PosSession, error) {
|
||||
field, value := "authname", strings.TrimSpace(req.Authname)
|
||||
if value == "" {
|
||||
field, value = "contactno", strings.TrimSpace(req.Contactno)
|
||||
}
|
||||
if value == "" {
|
||||
return nil, fmt.Errorf("an email or mobile number is required")
|
||||
}
|
||||
|
||||
rows, err := r.posLoginCandidates(field, value, req.Configid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// One message for "no such account" and for "wrong password", on purpose.
|
||||
// Distinguishing them turns the login into a directory of who banks here.
|
||||
if len(rows) == 0 {
|
||||
return nil, errPosLoginRejected
|
||||
}
|
||||
|
||||
// `authname` is not unique in this schema — live data has the same address
|
||||
// twice under one configid — so more than one row can come back. Resolving
|
||||
// that by taking the first would let the account a person *meant* be
|
||||
// shadowed by a stranger's, and on a POS that means billing into the wrong
|
||||
// tenant's books. Refused instead, with the fix the caller can act on.
|
||||
if len(rows) > 1 {
|
||||
return nil, fmt.Errorf(
|
||||
"more than one account uses these sign-in details; ask your administrator for the configid and send it with the login")
|
||||
}
|
||||
|
||||
// Inactive accounts never reach here — posLoginCandidates excludes them, so
|
||||
// that a deactivated duplicate cannot make a live login ambiguous.
|
||||
row := rows[0]
|
||||
|
||||
// Matches the web console's plaintext comparison, which is what the stored
|
||||
// column holds today. Constant-time so this endpoint at least does not add
|
||||
// a timing oracle on top.
|
||||
//
|
||||
// TODO: the password column is plaintext across the whole platform. Hashing
|
||||
// it is a migration touching every login path, not something this endpoint
|
||||
// can fix alone — but a POS token minted off a plaintext password is only
|
||||
// ever as good as that column.
|
||||
if strings.TrimSpace(row.Password) == "" {
|
||||
return nil, fmt.Errorf("this account has no password set; set one in the web console first")
|
||||
}
|
||||
if !constantTimeEqual(row.Password, req.Password) {
|
||||
return nil, errPosLoginRejected
|
||||
}
|
||||
|
||||
if row.Tenantid <= 0 {
|
||||
return nil, fmt.Errorf("this account is not attached to a tenant and cannot open a till")
|
||||
}
|
||||
|
||||
locations, err := r.posLoginLocations(row.Tenantid, row.Locationid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(locations) == 0 {
|
||||
return nil, fmt.Errorf("no active outlet is registered for this account")
|
||||
}
|
||||
|
||||
// Which outlet this terminal is standing in. A request may ask for one, but
|
||||
// only from the set the account already reaches.
|
||||
chosen := locations[0]
|
||||
if req.Locationid > 0 {
|
||||
match := false
|
||||
for _, loc := range locations {
|
||||
if loc.Locationid == req.Locationid {
|
||||
chosen, match = loc, true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !match {
|
||||
return nil, fmt.Errorf("this account cannot open a till at outlet %d", req.Locationid)
|
||||
}
|
||||
}
|
||||
|
||||
session := &models.PosSession{
|
||||
Userid: row.Userid,
|
||||
Fullname: strings.TrimSpace(row.Firstname + " " + row.Lastname),
|
||||
Email: row.Email,
|
||||
Roleid: row.Roleid,
|
||||
Tenantid: row.Tenantid,
|
||||
Storeid: fmt.Sprintf("%d", chosen.Locationid),
|
||||
Locationid: chosen.Locationid,
|
||||
Locationname: chosen.Locationname,
|
||||
Address: chosen.Address,
|
||||
Locations: locations,
|
||||
}
|
||||
|
||||
r.decoratePosSession(session)
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// posLoginCandidates finds the accounts matching a set of sign-in details.
|
||||
//
|
||||
// Returns a list rather than a row because `app_users` does not constrain
|
||||
// `authname` to be unique — not globally and not per configid. The caller
|
||||
// decides what an ambiguous match means; silently picking one here would bury
|
||||
// the decision in a LIMIT 1.
|
||||
//
|
||||
// The configid handling is the part worth explaining. The web console asks for
|
||||
// it because the browser knows which tenant portal it is on. A till does not:
|
||||
// somebody is standing at a counter typing an email and a password, and
|
||||
// demanding a number they have never seen would make the login unusable. So it
|
||||
// is honoured when sent and inferred when not — and inference that finds more
|
||||
// than one candidate is reported, never guessed.
|
||||
func (r *posRepository) posLoginCandidates(field, value string, configID int) ([]posLoginRow, error) {
|
||||
rows := make([]posLoginRow, 0, 2)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT userid, COALESCE(password, '') AS password, COALESCE(status, '') AS status,
|
||||
COALESCE(roleid, 0) AS roleid, COALESCE(configid, 0) AS configid,
|
||||
COALESCE(tenantid, 0) AS tenantid, COALESCE(locationid, 0) AS locationid,
|
||||
COALESCE(firstname, '') AS firstname, COALESCE(lastname, '') AS lastname,
|
||||
COALESCE(email, '') AS email
|
||||
FROM app_users
|
||||
WHERE LOWER(TRIM(%s)) = LOWER(TRIM(?))`, field)
|
||||
params := []interface{}{value}
|
||||
|
||||
if configID > 0 {
|
||||
query += ` AND configid = ?`
|
||||
params = append(params, configID)
|
||||
}
|
||||
|
||||
// Inactive accounts are excluded from the match rather than matched and
|
||||
// then refused. A deactivated duplicate would otherwise make a working
|
||||
// login ambiguous, which turns "this person left" into "nobody can open
|
||||
// the till".
|
||||
query += ` AND LOWER(COALESCE(status, 'active')) <> 'inactive' ORDER BY userid`
|
||||
|
||||
if err := r.db.Raw(query, params...).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// posLoginLocations lists the outlets an account may open a till at.
|
||||
//
|
||||
// A user pinned to one location gets that one alone; a tenant-level account
|
||||
// with locationid 0 — a proprietor with several shops — gets all of the
|
||||
// tenant's active outlets and picks at sign-in.
|
||||
//
|
||||
// Inactive outlets are excluded rather than listed and disabled: a till cannot
|
||||
// usefully trade at a closed shop, and offering it is an invitation to a
|
||||
// support call.
|
||||
func (r *posRepository) posLoginLocations(tenantID, pinned int) ([]models.PosLoginLocation, error) {
|
||||
rows := make([]models.PosLoginLocation, 0)
|
||||
|
||||
query := `
|
||||
SELECT locationid,
|
||||
COALESCE(locationname, '') AS locationname,
|
||||
COALESCE(address, '') AS address,
|
||||
COALESCE(city, '') AS city,
|
||||
COALESCE(status, '') AS status
|
||||
FROM tenantlocations
|
||||
WHERE tenantid = ? AND LOWER(COALESCE(status, 'active')) <> 'inactive'`
|
||||
params := []interface{}{tenantID}
|
||||
|
||||
if pinned > 0 {
|
||||
query += ` AND locationid = ?`
|
||||
params = append(params, pinned)
|
||||
}
|
||||
query += ` ORDER BY locationid`
|
||||
|
||||
if err := r.db.Raw(query, params...).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// decoratePosSession fills in what a receipt needs.
|
||||
//
|
||||
// The store name, GSTIN and address printed on a bill are a legal requirement
|
||||
// on a GST invoice, and the till had them as compile-time constants. Sending
|
||||
// them down with the session means a shop that corrects its GSTIN in the back
|
||||
// office sees the correction on its next receipt rather than at the next
|
||||
// rebuild.
|
||||
//
|
||||
// Failures here are swallowed: a missing tenant name is a cosmetic problem, and
|
||||
// refusing a sign-in over it would close a shop.
|
||||
func (r *posRepository) decoratePosSession(session *models.PosSession) {
|
||||
var tenant struct {
|
||||
Tenantname string
|
||||
Gstin string
|
||||
Contactno string
|
||||
Address string
|
||||
}
|
||||
|
||||
// `registrationno` is where this schema keeps the GST number — there is no
|
||||
// `gstin` column. Aliased rather than renamed through the stack so the till
|
||||
// receives it under the name it prints on a receipt.
|
||||
err := r.db.Raw(`
|
||||
SELECT COALESCE(tenantname, '') AS tenantname,
|
||||
COALESCE(registrationno, '') AS gstin,
|
||||
COALESCE(primarycontact, '') AS contactno,
|
||||
COALESCE(address, '') AS address
|
||||
FROM tenants WHERE tenantid = ? LIMIT 1`, session.Tenantid).Scan(&tenant).Error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
session.Tenantname = tenant.Tenantname
|
||||
session.Gstin = tenant.Gstin
|
||||
session.Phone = tenant.Contactno
|
||||
|
||||
// The outlet's own address wins — a chain's receipts must name the shop the
|
||||
// customer is standing in, not head office. The tenant address is only a
|
||||
// fallback for an outlet that has none recorded.
|
||||
if strings.TrimSpace(session.Address) == "" {
|
||||
session.Address = tenant.Address
|
||||
}
|
||||
}
|
||||
|
||||
// PosLocationAllowed reports whether a tenant owns an outlet.
|
||||
//
|
||||
// The check the whole session model rests on. Everything a terminal asks for
|
||||
// names a location, and this is what stops a valid token for one shop being
|
||||
// replayed against another.
|
||||
func (r *posRepository) PosLocationAllowed(tenantID, locationID int) (bool, error) {
|
||||
if tenantID <= 0 || locationID <= 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
var count int64
|
||||
err := r.db.Raw(
|
||||
`SELECT COUNT(1) FROM tenantlocations WHERE tenantid = ? AND locationid = ?`,
|
||||
tenantID, locationID,
|
||||
).Scan(&count).Error
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// errPosLoginRejected is the single answer to a bad email and a bad password.
|
||||
var errPosLoginRejected = fmt.Errorf("those sign-in details were not recognised")
|
||||
|
||||
// PosLoginRejected reports whether an error is a failed credential check, so
|
||||
// the controller can answer 401 for those and 500 for a database fault without
|
||||
// matching on message text.
|
||||
func PosLoginRejected(err error) bool { return err == errPosLoginRejected }
|
||||
|
||||
// constantTimeEqual compares two secrets without leaking their contents through
|
||||
// how long it took.
|
||||
//
|
||||
// Length is compared first and is deliberately allowed to leak — a password's
|
||||
// length is not the secret, and hashing to a fixed width just to hide it would
|
||||
// be more machinery than the exposure justifies.
|
||||
func constantTimeEqual(a, b string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
var diff byte
|
||||
for i := 0; i < len(a); i++ {
|
||||
diff |= a[i] ^ b[i]
|
||||
}
|
||||
return diff == 0
|
||||
}
|
||||
@@ -38,6 +38,11 @@ type PosRepository interface {
|
||||
IngestCustomers(batch models.PosCustomerBatch) (*models.PosAck, error)
|
||||
Catalogue(storeID, since string, page, pageSize int) (*models.PosCatalogueResponse, error)
|
||||
|
||||
// Sign-in. The outlet a terminal bills for is decided here, from the user's
|
||||
// own record, rather than being named by the till and believed.
|
||||
PosLogin(req models.PosLoginRequest) (*models.PosSession, error)
|
||||
PosLocationAllowed(tenantID, locationID int) (bool, error)
|
||||
|
||||
// Reading counter sales back out. Without these a committed bill is
|
||||
// unreachable from every screen in the product.
|
||||
Sales(f models.PosSalesFilter) (*models.PosSalesPage, error)
|
||||
|
||||
Reference in New Issue
Block a user