diff --git a/.gitattributes b/.gitattributes index 98cd08fe..88a3ee3d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,7 @@ * text=auto eol=lf /.github export-ignore +/bin export-ignore /tests export-ignore /js/tests export-ignore /.gitattributes export-ignore diff --git a/README.md b/README.md index 9a5b4d47..fd207637 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,12 @@ npm install @entity/keyring The [changelog](CHANGELOG.md) lists what each release changes, and the [upgrade guide](UPGRADE.md) covers anything you need to do when updating. +## What's Stable + +What the docs describe is what a release keeps to: the config options, the route names and paths, the middleware aliases, the `Keyring` facade and `Keyring::for($user)`, the factor and policy builders, the contracts in `Keyring\Contracts`, the events and their properties, the email types and what each is passed, the security log's entry types, the commands and their options, the testing helpers, and the browser package's exports. A change to any of those is called out in the [upgrade guide](UPGRADE.md), and before 1.0 a minor release (0.2, 0.3) may make one. + +Everything else in `src/` is how Keyring does it and can change in any release: controllers, pipeline steps' internals, and anything in `Keyring\Support`. If you find yourself extending one of those, [Extending Keyring](docs/extending.md) probably has a supported way, and an issue is welcome when it doesn't. + ## Security Vulnerabilities Please don't open a public issue for a security problem. See the [security policy](SECURITY.md) for how to report one. @@ -109,6 +115,8 @@ composer check # everything CI runs: Rector (dry run), Pint, PHPStan and Pes Run `composer check` before opening a pull request. +`bin/ci` runs every job the GitHub workflow does on your own machine: the checks above, the oldest dependencies Keyring allows, PostgreSQL, MySQL (in Docker) and the browser package. `bin/ci tests js` runs only the jobs you name. Run one at a time. + The race tests run operations in separate processes against a real database, so they need PostgreSQL or MySQL and run as their own suite (CI runs them on both): ```bash diff --git a/UPGRADE.md b/UPGRADE.md index 134996fc..0cca5824 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,3 +1,5 @@ # Upgrade Guide Keyring has no tagged release yet, so there's nothing to upgrade from. This guide starts with the first release, and will list anything you need to change when updating from one release to the next. + +What counts as a change you'd need to act on is in the README's [What's Stable](README.md#whats-stable). A test (`tests/Feature/PublicApiTest.php`) fails when a route, middleware alias, facade method, contract, event or email type is renamed or removed, so one can't change without an entry here. diff --git a/bin/ci b/bin/ci new file mode 100755 index 00000000..69e74efe --- /dev/null +++ b/bin/ci @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# +# Everything .github/workflows/tests.yml runs, on this machine: for when +# GitHub can't run it, or before pushing. +# +# bin/ci every job +# bin/ci tests js only the jobs named: tests, lowest, pgsql, mysql, js +# +# PostgreSQL is whichever server these point at (the workflow's own values +# unless set): PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE. The database +# has to exist. MySQL is started in Docker for the run, on MYSQL_PORT (3307), +# bound to this machine only. +# +# One run at a time: the installer's tests publish into the test app every +# run shares, so two at once fail each other. + +set -uo pipefail +cd "$(dirname "$0")/.." + +jobs=("$@") +[ ${#jobs[@]} -eq 0 ] && jobs=(tests lowest pgsql mysql js) + +failed=() + +step() { + printf '\n\033[1m▸ %s\033[0m\n' "$*" + "$@" || return 1 +} + +tests() { + step composer audit --abandoned=report && + step vendor/bin/rector --dry-run && + step vendor/bin/pint --test && + step vendor/bin/phpstan analyse --no-progress && + step vendor/bin/phpstan analyse -c phpstan.stubs.neon --no-progress && + step vendor/bin/pest --compact +} + +# The oldest versions composer.json allows, in a copy, so this checkout's +# vendor directory and lock file stay as they are. +lowest() { + local copy index + copy=$(mktemp -d) && index=$(mktemp -u) || return 1 + + GIT_INDEX_FILE=$index git read-tree HEAD && + GIT_INDEX_FILE=$index git checkout-index -a --prefix="$copy/" && + ( + cd "$copy" && + step composer remove --dev calebdw/phpstan-laravel --no-update --no-interaction --quiet && + step composer update --prefer-lowest --prefer-stable --no-interaction --prefer-dist --quiet && + step vendor/bin/pest --compact + ) + local status=$? + + rm -rf "$copy" "$index" + + return $status +} + +database() { + step vendor/bin/pest --compact && step vendor/bin/pest --compact --testsuite=Concurrency +} + +pgsql() { + DB_CONNECTION=pgsql DB_HOST=${PGHOST:-127.0.0.1} DB_PORT=${PGPORT:-5432} DB_DATABASE=${PGDATABASE:-keyring} \ + DB_USERNAME=${PGUSER:-postgres} DB_PASSWORD=${PGPASSWORD-password} database +} + +mysql() { + local name=keyring-ci-mysql port=${MYSQL_PORT:-3307} + + docker run -d --rm --name "$name" -e MYSQL_DATABASE=keyring -e MYSQL_ROOT_PASSWORD=password \ + -p "127.0.0.1:$port:3306" mysql:8.4 >/dev/null || return 1 + + # It answers a ping before it takes connections, so ask it a question. + for _ in $(seq 60); do + docker exec "$name" mysql -ppassword -e 'select 1' keyring >/dev/null 2>&1 && break + sleep 2 + done + + DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=$port DB_DATABASE=keyring DB_USERNAME=root DB_PASSWORD=password database + local status=$? + + docker stop "$name" >/dev/null + + return $status +} + +js() { + ( + cd js && + step bun install --frozen-lockfile && + step bun audit && + step bun run typecheck && + step bun test --randomize + ) +} + +for job in "${jobs[@]}"; do + case $job in + tests | lowest | pgsql | mysql | js) + printf '\n\033[1;34m━━ %s ━━\033[0m\n' "$job" + $job || failed+=("$job") + ;; + *) + echo "Unknown job: $job. Pick from: tests, lowest, pgsql, mysql, js." >&2 + exit 2 + ;; + esac +done + +echo +if [ ${#failed[@]} -gt 0 ]; then + printf '\033[1;31mFailed: %s\033[0m\n' "${failed[*]}" + exit 1 +fi + +printf '\033[1;32mPassed: %s\033[0m\n' "${jobs[*]}" diff --git a/tests/Feature/PublicApiTest.php b/tests/Feature/PublicApiTest.php new file mode 100644 index 00000000..a37a1805 --- /dev/null +++ b/tests/Feature/PublicApiTest.php @@ -0,0 +1,55 @@ + collect(new ReflectionClass($class)->getMethods(ReflectionMethod::IS_PUBLIC)) + ->reject(fn (ReflectionMethod $method) => $method->isConstructor() || Str::startsWith($method->getName(), '__')) + ->map(fn (ReflectionMethod $method) => $method->getName()) + ->sort()->values()->all(); + + $classes = fn (string $directory, string $namespace) => collect(File::allFiles(__DIR__.'/../../src/'.$directory)) + ->map(fn (SplFileInfo $file) => $namespace.'\\'.str_replace('/', '\\', Str::beforeLast($file->getRelativePathname(), '.php'))) + ->sort()->values(); + + $api = [ + 'routes' => collect(app('router')->getRoutes()->getRoutes()) + ->filter(fn ($route) => $route->getName() !== null) + ->mapWithKeys(fn ($route) => [$route->getName() => implode('|', array_diff($route->methods(), ['HEAD'])).' /'.ltrim($route->uri(), '/')]) + ->sortKeys()->all(), + 'middleware' => collect(app('router')->getMiddleware())->keys()->filter(fn (string $alias) => Str::startsWith($alias, 'keyring'))->sort()->values()->all(), + 'features' => Features::all(), + 'emails' => KeyringManager::NOTIFICATIONS, + 'facade' => $methods(KeyringManager::class), + 'user' => $methods(UserKeyring::class), + 'contracts' => $classes('Contracts', 'Keyring\\Contracts')->mapWithKeys(fn (string $contract) => [$contract => $methods($contract)])->all(), + 'events' => $classes('Events', 'Keyring\\Events')->mapWithKeys(fn (string $event) => [ + $event => collect(new ReflectionClass($event)->getProperties(ReflectionProperty::IS_PUBLIC))->map->getName()->sort()->values()->all(), + ])->all(), + ]; + + $path = __DIR__.'/../Fixtures/public-api.json'; + + if (getenv('UPDATE_PUBLIC_API')) { + File::put($path, json_encode($api, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n"); + } + + expect($api)->toEqual(json_decode(File::get($path), true, flags: JSON_THROW_ON_ERROR)); +}); diff --git a/tests/Fixtures/public-api.json b/tests/Fixtures/public-api.json new file mode 100644 index 00000000..1b4cc4d3 --- /dev/null +++ b/tests/Fixtures/public-api.json @@ -0,0 +1,484 @@ +{ + "routes": { + "keyring.authenticators.confirm": "POST /user/authenticators/{factor}/confirm", + "keyring.authenticators.destroy": "DELETE /user/authenticators/{authenticator}", + "keyring.authenticators.store": "POST /user/authenticators/{factor}", + "keyring.authenticators.update": "PATCH /user/authenticators/{authenticator}", + "keyring.confirm.challenge": "GET /confirm/{factor?}", + "keyring.confirm.send": "POST /confirm/{factor}/send", + "keyring.confirm.verify": "POST /confirm/{factor}", + "keyring.devices.destroy": "DELETE /user/devices/{device}", + "keyring.devices.destroy-others": "DELETE /user/devices", + "keyring.devices.index": "GET /user/devices", + "keyring.devices.report": "GET /devices/{device}/report", + "keyring.devices.report.store": "POST /devices/{device}/report", + "keyring.email.confirm": "GET /email-changes/{change}/confirm/{token}", + "keyring.email.confirm.store": "POST /email-changes/{change}/confirm", + "keyring.email.destroy": "DELETE /user/email", + "keyring.email.revert": "GET /email-changes/{change}/revert/{token}", + "keyring.email.revert.store": "POST /email-changes/{change}/revert", + "keyring.email.show": "GET /user/email", + "keyring.email.store": "POST /user/email", + "keyring.login.challenge": "GET /login/challenge/{factor?}", + "keyring.login.factor": "POST /login/{factor}", + "keyring.login.options": "GET /login/{factor}/options", + "keyring.login.send": "POST /login/challenge/{factor}/send", + "keyring.login.verify": "POST /login/challenge/{factor}", + "keyring.sessions.destroy": "DELETE /user/sessions/{session}", + "keyring.sessions.destroy-others": "DELETE /user/sessions", + "keyring.sessions.index": "GET /user/sessions", + "login": "GET /login", + "login.store": "POST /login", + "logout": "POST /logout", + "password.email": "POST /forgot-password", + "password.request": "GET /forgot-password", + "password.reset": "GET /reset-password/{token}", + "password.update": "POST /reset-password", + "register": "GET /register", + "register.store": "POST /register", + "user-password.update": "PUT /user/password", + "verification.notice": "GET /email/verify", + "verification.send": "POST /email/verification-notification", + "verification.verify": "GET /email/verify/{id}/{hash}", + "verification.verify.store": "POST /email/verify/{id}/{hash}" + }, + "middleware": [ + "keyring", + "keyring.enrolled", + "keyring.fresh", + "keyring.password", + "keyring.session", + "keyring.signed" + ], + "features": [ + "registration", + "reset-passwords", + "email-verification", + "update-passwords", + "manage-authenticators", + "devices", + "email-changes", + "security-log" + ], + "emails": [ + "new_device", + "password_changed", + "authenticator_added", + "authenticator_removed", + "second_factor_failed", + "recovery_code_used", + "recovery_codes_generated", + "suspicious_activity", + "clone_suspected", + "account_locked", + "email_changed", + "email_change_reverted", + "verification_code", + "confirm_email_change", + "email_change_notice", + "email_address_in_use", + "already_registered" + ], + "facade": [ + "activity", + "allowEnrollmentWhen", + "allowSignInWhen", + "allowsEnrollment", + "allowsSignIn", + "attempt", + "authenticatorModel", + "belongsToGuard", + "cancelPasswordChange", + "createUsersUsing", + "dangerouslyChangedSteps", + "describeDevice", + "describeDevicesUsing", + "deviceModel", + "email", + "extend", + "factor", + "factors", + "failureCountModel", + "fake", + "findUser", + "findUsersUsing", + "for", + "guard", + "hasFactor", + "hasNotification", + "hidesRegisteredAddresses", + "linkRoot", + "linkRootUsing", + "normalizeUsername", + "normalizeUsernamesUsing", + "notification", + "notifications", + "page", + "pendingChangeModel", + "pipeline", + "policy", + "protectedAttributes", + "provider", + "recordIpsUsing", + "recordedIp", + "registered", + "render", + "require", + "requirePasswordChange", + "requiredNotification", + "requirementFor", + "requiresPasswordChange", + "resetUserPasswordsUsing", + "respondWith", + "response", + "risk", + "routes", + "securityEventModel", + "signInAfterRegistering", + "signsInAfterRegistering", + "statusMessage", + "steps", + "unlock", + "updateUserPasswordsUsing", + "useAuthenticatorModel", + "useDeviceModel", + "useFailureCountModel", + "usePendingChangeModel", + "useSecurityEventModel", + "user", + "username", + "validateEmailChangesUsing", + "withoutProtection" + ], + "user": [ + "all", + "canMeet", + "canSignIn", + "default", + "find", + "has", + "hasFactorToRecover", + "hasRecoveryCodes", + "hasSecondFactor", + "of", + "reachable", + "refresh", + "shouldReplaceRecoveryCodes", + "unregistered", + "usefulFor", + "without", + "withoutFallbacks" + ], + "contracts": { + "Keyring\\Contracts\\CreatesNewUsers": [ + "create", + "validate" + ], + "Keyring\\Contracts\\DiscoverableFactor": [ + "answersChallenges", + "attested", + "authenticators", + "categories", + "challenge", + "deviceBound", + "errorKey", + "identificationRules", + "identify", + "key", + "limits", + "loginOptions", + "phishingResistant", + "present", + "priority", + "rules", + "stall", + "startsLogin", + "verify" + ], + "Keyring\\Contracts\\Enrollable": [ + "attested", + "authenticators", + "beginEnrollment", + "categories", + "challenge", + "confirmEnrollment", + "deviceBound", + "enrollmentRules", + "errorKey", + "key", + "limits", + "multiple", + "phishingResistant", + "present", + "priority", + "rules", + "verify" + ], + "Keyring\\Contracts\\Factor": [ + "attested", + "authenticators", + "categories", + "challenge", + "deviceBound", + "errorKey", + "key", + "limits", + "phishingResistant", + "present", + "priority", + "rules", + "verify" + ], + "Keyring\\Contracts\\LocatesIps": [ + "locate" + ], + "Keyring\\Contracts\\PrimaryFactor": [ + "answersChallenges", + "attested", + "authenticators", + "categories", + "challenge", + "deviceBound", + "errorKey", + "identificationRules", + "identify", + "key", + "limits", + "phishingResistant", + "present", + "priority", + "rules", + "stall", + "startsLogin", + "verify" + ], + "Keyring\\Contracts\\ResetsUserPasswords": [ + "reset" + ], + "Keyring\\Contracts\\Responses\\AuthenticatedResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\ChallengeResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\ConfirmationRequiredResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\EnrollmentRequiredResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\FailedResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\LockoutResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\LogoutResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\PasswordChangeRequiredResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\RegisterResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\SignedOutResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\StatusResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\Responses\\VerifiedResponse": [ + "toResponse" + ], + "Keyring\\Contracts\\SendsCodes": [ + "attested", + "authenticators", + "categories", + "challenge", + "deviceBound", + "errorKey", + "key", + "limits", + "phishingResistant", + "present", + "priority", + "rules", + "send", + "verify" + ], + "Keyring\\Contracts\\SessionRegistry": [ + "find", + "forUser", + "prune", + "replace", + "revoke", + "revokeAll", + "revokeDevice", + "revokeEveryone", + "save", + "update" + ], + "Keyring\\Contracts\\Signal": [ + "assess", + "checkpoints" + ], + "Keyring\\Contracts\\TrustsAuthenticators": [ + "roots" + ], + "Keyring\\Contracts\\UpdatesUserPasswords": [ + "update" + ], + "Keyring\\Contracts\\ValidatesEmailChanges": [ + "validate" + ] + }, + "events": { + "Keyring\\Events\\AccessRefused": [ + "id", + "resource", + "user" + ], + "Keyring\\Events\\AccountLocked": [ + "factor", + "user" + ], + "Keyring\\Events\\Attempting": [ + "factor", + "purpose", + "request" + ], + "Keyring\\Events\\Authenticated": [ + "attempt", + "device", + "user" + ], + "Keyring\\Events\\AuthenticatorAdded": [ + "authenticator", + "user" + ], + "Keyring\\Events\\AuthenticatorRemovalRefused": [ + "authenticator", + "user" + ], + "Keyring\\Events\\AuthenticatorRemoved": [ + "authenticator", + "user" + ], + "Keyring\\Events\\CloneSuspected": [ + "authenticator" + ], + "Keyring\\Events\\Confirmed": [ + "attempt", + "user" + ], + "Keyring\\Events\\DeviceRevoked": [ + "device", + "reported", + "user" + ], + "Keyring\\Events\\EmailChangeRequested": [ + "change", + "user" + ], + "Keyring\\Events\\EmailChangeReverted": [ + "change", + "user" + ], + "Keyring\\Events\\EmailChanged": [ + "change", + "user" + ], + "Keyring\\Events\\EnrollmentRefused": [ + "factor", + "reason", + "user" + ], + "Keyring\\Events\\FactorChallenged": [ + "attempt", + "authenticator" + ], + "Keyring\\Events\\FactorFailed": [ + "attempt", + "authenticator", + "factor", + "request" + ], + "Keyring\\Events\\FactorVerified": [ + "attempt", + "authenticator", + "verification" + ], + "Keyring\\Events\\LinkRefused": [ + "link", + "reason", + "user" + ], + "Keyring\\Events\\Lockout": [ + "factor", + "request", + "retryAfter" + ], + "Keyring\\Events\\LoggedOut": [ + "user" + ], + "Keyring\\Events\\NewDeviceSignedIn": [ + "device", + "user" + ], + "Keyring\\Events\\PasswordChangeRequired": [ + "reason", + "user" + ], + "Keyring\\Events\\PasswordChanged": [ + "user" + ], + "Keyring\\Events\\PasswordReset": [ + "user" + ], + "Keyring\\Events\\ProtectionBypassed": [ + "reason" + ], + "Keyring\\Events\\RateLimited": [ + "limiter", + "retryAfter", + "route", + "user" + ], + "Keyring\\Events\\RecoveryCodeUsed": [ + "authenticator", + "remaining" + ], + "Keyring\\Events\\RecoveryCodesGenerated": [ + "authenticator", + "user" + ], + "Keyring\\Events\\RememberMeReused": [ + "session", + "user" + ], + "Keyring\\Events\\RiskAssessed": [ + "action", + "checkpoint", + "risk", + "user" + ], + "Keyring\\Events\\SessionEnded": [ + "reason", + "user" + ], + "Keyring\\Events\\SessionResumed": [ + "session", + "user" + ], + "Keyring\\Events\\SessionsRevoked": [ + "count", + "user" + ], + "Keyring\\Events\\VerificationRefused": [ + "attempt", + "factor", + "skipped" + ] + } +}