devices

package
v0.298.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package devices is muster's paired-phone store: the native Android app's DEVICE CREDENTIAL (`mdv_…`) and the one-time PAIRING CODE that mints it (migration 0039; docs/design/android.md, "The device credential").

The flow, in one line each:

  • A signed-in web session asks for a pairing code (CreatePairingCode, the caller's own principal). Any valid signed-in session may ask, however long ago it signed in (an operator decision; internal/api has no recent-sign-in window for this). The session's sign-in time is stored with the code and becomes the device's paired_signin_at, which the revocation rule below reads.
  • The app redeems the code (Redeem) for the device credential, sending the device's name, app version and its step-up public key. The code is single use and lives PairingCodeTTL.
  • Every request the app makes presents the credential (Authenticate).

🔴 A DEVICE CREDENTIAL CANNOT MINT ANOTHER. A code is created only under a browser session's principal (internal/api's session tier), and the device door refuses an `mdv_` credential everywhere outside /api/device/*. So "a token cannot mint a token" holds for this credential as it does for `mst_`.

🔴 EVERY REVOCATION DELETES THE PHONE: Remove and unpair here, and a disable, a password reset and a Sign out everywhere in internal/users (deleteDevicesTx), each in the transaction that records it. Its push subscription goes with it. THE RULE BELOW IS THE SECOND WALL, READ ON EVERY REQUEST WITH NOTHING CACHED, for a row that outlived its revocation: Authenticate joins the device to its owner's users row and refuses the credential when:

  • the device row is gone (the owner removed it on Account → Devices, or the app unpaired itself);
  • the owner is disabled (ErrUserDisabled);
  • the pairing session's SIGN-IN is at or before the owner's session cutoff, users.sessions_not_before, which every disable and password reset moves (ErrSessionEnded);
  • the pairing session's sign-in is at or before the owner's latest "Sign out everywhere", users.signed_out_at (ErrSignedOut). Only gotrue mode stamps that column, so this path exists in gotrue mode only. It is the design's RECOMMENDATION, not an operator requirement: it is what "everywhere" is expected to mean for a phone, and it is stricter than `mst_` tokens, which Sign out everywhere does not revoke (docs/decisions.md).

"At or before" is in whole seconds, the rule the session tier and the send queue already use (a sign-in in the cutoff's own second is refused).

🔴 TWO KINDS OF METHOD, AS IN internal/push. CreatePairingCode, List and Remove run under the CALLER's principal, and devices and device_pairing_codes are under FORCE row-level security, so they see only that user's rows. Redeem and Authenticate cannot: each is how a request's owner is LEARNED (a code or a credential, by its hash). They run under authz.System through this package's one helper, sys (ledgered in internal/authz/ledger_test.go), and hand on only the row's owner.

Index

Constants

View Source
const (
	// NoncePrefix starts every challenge nonce.
	NoncePrefix = "mdc_"
	// ChallengeTTL is how long a challenge can be spent.
	ChallengeTTL = 2 * time.Minute
	// MessageVersion is the first line of every signed message.
	MessageVersion = "muster-device-action-v1"
)
View Source
const (
	// TokenPrefix starts every device credential. The doors tell it from every
	// other credential by this prefix before any database read.
	TokenPrefix = "mdv_"
	// CodePrefix starts every pairing code.
	CodePrefix = "mdp_"

	// PairingCodeTTL is how long a pairing code can be redeemed.
	PairingCodeTTL = 60 * time.Second
	// MaxPerOwner bounds one user's paired devices, the same bound push
	// subscriptions have (push.MaxDevicesPerOwner).
	MaxPerOwner = 20
	// MaxNameLen and MaxAppVersionLen bound the labels the app sends.
	MaxNameLen       = 100
	MaxAppVersionLen = 64
	// LastSeenGranularity is how stale last_seen_at may get before an
	// authentication rewrites it.
	LastSeenGranularity = time.Minute
)
View Source
const (
	KeyBiometric             = "biometric"
	KeyBiometricOrCredential = "biometric_or_credential"
)

The step-up key's type (docs/design/android.md, "The step-up key"): biometric-only by default; biometric-or-device-PIN only when the operator allows PIN keys (MUSTER_ANDROID_ALLOW_PIN_KEYS).

View Source
const (
	LevelSoftware           = "software"
	LevelTrustedEnvironment = "trusted_environment"
	LevelStrongBox          = "strongbox"
	LevelUnknownSecure      = "unknown_secure"
)

The Keystore security levels the app reports (KeyInfo.getSecurityLevel). A software key is refused: until key attestation exists the server trusts the app's report, and it refuses the one level that says "not hardware".

Variables

View Source
var (
	// ErrNoStepUpKey: the device paired without a step-up key (read-only).
	ErrNoStepUpKey = errors.New("devices: this device has no step-up key, so it can take no action")
	// ErrChallengeInvalid: no such challenge for this device, or one bound to
	// another action, target or text.
	ErrChallengeInvalid = errors.New("devices: no such challenge for this action")
	// ErrChallengeUsed: the challenge was already spent (a replay, or a retry
	// of a failed attempt).
	ErrChallengeUsed = errors.New("devices: this challenge was already used")
	// ErrChallengeExpired: the challenge lapsed (ChallengeTTL).
	ErrChallengeExpired = errors.New("devices: this challenge has expired")
	// ErrBadSignature: the signature does not verify against the device's
	// step-up key over the challenge's message.
	ErrBadSignature = errors.New("devices: the signature does not verify")
)
View Source
var (
	// ErrBadToken: not a live device credential — malformed, unknown, or the
	// device was removed. One error for all three.
	ErrBadToken = errors.New("devices: invalid or removed device credential")
	// ErrBadCode: not a redeemable pairing code — malformed, unknown, used or
	// expired. One error for all four.
	ErrBadCode = errors.New("devices: invalid, used or expired pairing code")
	// ErrUserDisabled: the device's owner is disabled.
	ErrUserDisabled = errors.New("devices: the device's user is disabled")
	// ErrSessionEnded: the pairing session's sign-in is at or before the
	// owner's session cutoff (a disable or a password reset moved it).
	ErrSessionEnded = errors.New("devices: the session that paired this device has been ended")
	// ErrSignedOut: the pairing session's sign-in is at or before the owner's
	// latest Sign out everywhere.
	ErrSignedOut = errors.New("devices: the owner signed out everywhere after this device was paired")
	// ErrTooMany: the owner already has MaxPerOwner devices.
	ErrTooMany = fmt.Errorf("devices: a user may pair at most %d devices; remove one on the account page", MaxPerOwner)
	// ErrInvalid: a label or the step-up key is not acceptable.
	ErrInvalid = errors.New("devices: invalid device details")
	// ErrNoUser: a session-tier call with no user principal.
	ErrNoUser = errors.New("devices: no user principal on this context")
	// ErrNoSignIn: a pairing code was asked for with no sign-in time.
	ErrNoSignIn = errors.New("devices: a pairing code needs the session's sign-in time")
	// ErrKeyNotAllowed: the step-up key's kind or security level is one this
	// server refuses (a software key always; a biometric-or-PIN key while the
	// PIN-key policy is off).
	ErrKeyNotAllowed = errors.New("devices: this step-up key is not accepted")
)

Functions

func CodeShapeOK

func CodeShapeOK(s string) bool

CodeShapeOK reports whether s is shaped like a minted pairing code.

func DecodeSignature

func DecodeSignature(s string) ([]byte, error)

DecodeSignature reads a base64 signature (standard or URL alphabet, padded or not).

func LiveSQL

func LiveSQL(dev, usr string) string

LiveSQL is ownerRefusal as a SQL predicate over a devices alias and its owner's users alias: true while the device's owner may still hold it. It is the SAME rule, for the readers that select rather than authenticate (the push fan-out's android rows, internal/push), and TestTheSQLRuleIsTheGoRule pins the two to each other.

func LooksLike

func LooksLike(s string) bool

LooksLike reports whether s carries the device-credential prefix. It decides which DOOR a credential is for, not whether it is valid.

func Message

func Message(nonce string, c Challenge) string

Message is the exact text a device signs for nonce and c: MessageVersion, the nonce, the action, the target and the hex sha256 of the text ("" for none), one per line, joined by "\n", no trailing newline, UTF-8. The signature is ECDSA P-256 over its SHA-256 (Java's "SHA256withECDSA"), DER encoded.

func Object

func Object(id int64) string

Object is the audit_log `object` a device's rows carry.

func ParseStepUpKey

func ParseStepUpKey(s string) ([]byte, error)

ParseStepUpKey decodes a step-up public key: base64 SubjectPublicKeyInfo DER of an EC P-256 key (the Android Keystore's KeyProperties.KEY_ALGORITHM_EC with secp256r1). It returns the DER to store. Empty is no key.

func ShapeOK

func ShapeOK(s string) bool

ShapeOK reports whether s is shaped like a minted device credential.

func TextHash

func TextHash(text string) []byte

TextHash is the sha256 of text, as a challenge binds it.

Types

type Challenge

type Challenge struct {
	DeviceID int64
	// Action is the action's wire id (docs/design/android.md, "Action ids").
	Action string
	// Target is the action's target (an ask's id).
	Target string
	// TextSHA256 is the sha256 of the exact text the action carries; nil for
	// an action that carries none.
	TextSHA256 []byte
}

Challenge is what a signed action is bound to.

type Device

type Device struct {
	ID         int64
	OwnerID    int64
	Name       string
	AppVersion string
	// HasStepUpKey: the device registered a step-up public key at pairing. A
	// phone without an acceptable key pairs without one (read-only).
	HasStepUpKey bool
	// KeyType and KeyLevel are the step-up key's type and reported Keystore
	// security level; empty with no key.
	KeyType  string
	KeyLevel string
	// PairedSigninAt is the pairing session's sign-in time, which every
	// revocation check compares against.
	PairedSigninAt time.Time
	CreatedAt      time.Time
	LastSeenAt     *time.Time
	// PushRegistered: the device holds a push subscription (List only).
	PushRegistered bool
}

Device is one paired device's record. It never carries the credential or its hash.

type PGStore

type PGStore struct {
	// contains filtered or unexported fields
}

PGStore is Store over Postgres (migration 0039).

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG returns the store over pool.

func (*PGStore) Authenticate

func (s *PGStore) Authenticate(ctx context.Context, token string) (Device, error)

Authenticate implements Store. See the package doc for the refusals.

🔴 THE SHAPE CHECK COMES FIRST AND COSTS NO I/O. last_seen_at is best effort: a failure to write it never refuses a live credential.

func (*PGStore) CreateChallenge

func (s *PGStore) CreateChallenge(ctx context.Context, c Challenge, allowPIN bool) (string, time.Time, error)

CreateChallenge mints a challenge for c under ctx's principal (the device's owner), returning its nonce ONCE and when it expires. ErrNoStepUpKey for a device without a key; ErrKeyNotAllowed for a biometric-or-PIN key while the server refuses them (allowPIN false).

func (*PGStore) CreatePairingCode

func (s *PGStore) CreatePairingCode(ctx context.Context, signinAt time.Time) (string, time.Time, error)

CreatePairingCode implements Store. signinAt is the pairing session's sign-in time (stepup.AuthTime); a zero one is refused, never stored as "no sign-in".

func (*PGStore) List

func (s *PGStore) List(ctx context.Context) ([]Device, error)

List implements Store.

func (*PGStore) RecordAction

func (s *PGStore) RecordAction(ctx context.Context, c Challenge, outcome string) error

RecordAction appends the audit row of a verified signed action, AFTER it was attempted, under ctx's principal: device.action naming the device, the action, its target, the text's hash and its OUTCOME — the ask's new status when it was performed ("answered", "cancelled"), or the refusal's code ("not_open", "not_found", …) — so a refused action never reads as one done.

func (*PGStore) Redeem

func (s *PGStore) Redeem(ctx context.Context, code string, in PairIn) (string, Device, error)

Redeem implements Store.

🔴 IT TAKES THE OWNER'S CREDENTIALS LOCK (users.LockCredentialsTx), so the device cap cannot be raced past, and it re-checks the owner (disabled, the cutoff, the latest sign-out everywhere) against the code's sign-in time with the same rule Authenticate uses: a code minted by a session that has since been ended pairs nothing. The code is spent only by a pairing that commits.

func (*PGStore) Remove

func (s *PGStore) Remove(ctx context.Context, id int64) (bool, error)

Remove implements Store. The row is DELETED, so the credential stops working on its next request and the device's push subscription goes with it (ON DELETE CASCADE). The device's own unpair (DELETE /api/device) is this call under the device's owner.

func (*PGStore) SpendChallenge

func (s *PGStore) SpendChallenge(ctx context.Context, nonce string, c Challenge, sig []byte, allowPIN bool) error

SpendChallenge spends nonce for c under ctx's principal and verifies sig over its message with the device's step-up key; nil means the action may proceed. It writes no audit row: the action has not happened yet, and may still be refused (an ask already settled, another owner's) — the caller records the OUTCOME once it knows it (RecordAction). See the file header for why a refusal still spends the nonce.

type PairIn

type PairIn struct {
	Name       string
	AppVersion string
	// StepUpKey is the step-up public key as SubjectPublicKeyInfo DER, base64
	// (standard or URL alphabet, padded or not). Empty: no key (read-only).
	StepUpKey string
	// KeyType (KeyBiometric | KeyBiometricOrCredential) and KeyLevel (the
	// Keystore security level) describe StepUpKey; both empty with no key.
	KeyType  string
	KeyLevel string
	// AllowPINKeys is the SERVER's policy (MUSTER_ANDROID_ALLOW_PIN_KEYS),
	// set by the handler, never read from the request.
	AllowPINKeys bool
}

PairIn is what the app sends with a pairing code.

type Store

type Store interface {
	// CreatePairingCode mints a pairing code for ctx's user, recording the
	// session's sign-in time. Session tier only.
	CreatePairingCode(ctx context.Context, signinAt time.Time) (code string, expiresAt time.Time, err error)
	// Redeem spends a pairing code and pairs a device, returning the
	// credential ONCE. Public: the code is the authority.
	Redeem(ctx context.Context, code string, in PairIn) (token string, d Device, err error)
	// Authenticate resolves a credential to its live device, or refuses it
	// (ErrBadToken, ErrUserDisabled, ErrSessionEnded, ErrSignedOut).
	Authenticate(ctx context.Context, token string) (Device, error)
	// List is ctx's user's devices, newest first.
	List(ctx context.Context) ([]Device, error)
	// Remove deletes ctx's user's device id (its push subscription goes with
	// it). found is false when the user has no such device.
	Remove(ctx context.Context, id int64) (found bool, err error)
	// CreateChallenge and SpendChallenge are a signed action's two halves
	// (challenge.go), under the device owner's principal.
	CreateChallenge(ctx context.Context, c Challenge, allowPIN bool) (nonce string, expiresAt time.Time, err error)
	SpendChallenge(ctx context.Context, nonce string, c Challenge, sig []byte, allowPIN bool) error
	// RecordAction audits a verified action's outcome (challenge.go).
	RecordAction(ctx context.Context, c Challenge, outcome string) error
}

Store is the device store.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL