Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
ci(postman): make the Customers folder runnable end to end
Ronald A. Richardson09e5876ee2d3
diff --git a/.github/actions/postman-contract/action.yml b/.github/actions/postman-contract/action.ymlindex cd3c4f56..389ad15d 100644--- a/.github/actions/postman-contract/action.yml+++ b/.github/actions/postman-contract/action.yml@@ -20,6 +20,31 @@ inputs:description: API version namespace.required: falsedefault: v1+ customer-identity:+ description: >-+ Email used as the customer identity throughout the "Customers" folder. Must be a+ real-looking email — CustomerController::requestCreationCode rejects a non-email+ when mode=email. Deliberately stable across runs: the contract job wipes the+ database each run, and the signup flow is idempotent regardless.+ required: false+ default: [email protected]+ customer-password:+ description: Password for the seeded CI customer. Minimum 8 characters.+ required: false+ default: CiCustomerPassw0rd!+ customer-phone:+ description: >-+ Phone for the seeded CI customer, E.164. Request Customer Login SMS resolves a+ user by this number, and 400s if it does not match one.+ required: false+ default: '+15555550123'+ customer-verification-code:+ description: >-+ Verification code seeded into the database and injected as {{verification_code}}.+ Both sides read this one input, so the seeded rows and the collection can never+ drift apart. Quoted because unquoted 000000 is YAML for the integer 0.+ required: false+ default: '000000'postman-ref:description: Ref of the fleetbase/postman repo to check out.required: false@@ -51,16 +76,31 @@ runs:id: keyif: steps.pmauth.outputs.available == 'true'shell: bash+ env:+ CUSTOMER_IDENTITY: ${{ inputs.customer-identity }}+ CUSTOMER_PASSWORD: ${{ inputs.customer-password }}+ CUSTOMER_PHONE: ${{ inputs.customer-phone }}+ VERIFICATION_CODE: ${{ inputs.customer-verification-code }}run: |set -uo pipefail# Run the mint snippet via `tinker --execute="eval(base64_decode(...))"`.# Piping a file with a <?php tag to tinker triggers a PsySH parse error, and# inlining the code would let the shell expand its $variables — base64+eval# sidesteps both. Capture stdout+stderr so failures are diagnosable.+ # The customer fixture values are passed as container env vars rather than+ # interpolated into the snippet: the snippet is base64'd precisely so the shell+ # cannot touch it, and `-e` keeps these inputs the single source of truth shared+ # with the --env-var injection below.CODE="$(base64 scripts/ci/mint-api-key.php | tr -d '\n')"- OUT="$(docker compose exec -T application php artisan tinker --execute="eval(base64_decode('${CODE}'));" 2>&1 || true)"+ OUT="$(docker compose exec -T \+ -e "CI_CUSTOMER_IDENTITY=${CUSTOMER_IDENTITY}" \+ -e "CI_CUSTOMER_PHONE=${CUSTOMER_PHONE}" \+ -e "CI_CUSTOMER_PASSWORD=${CUSTOMER_PASSWORD}" \+ -e "CI_CUSTOMER_VERIFICATION_CODE=${VERIFICATION_CODE}" \+ application php artisan tinker --execute="eval(base64_decode('${CODE}'));" 2>&1 || true)"KEY="$(printf '%s\n' "$OUT" | grep -oE 'flb_(live|test)_[A-Za-z0-9_-]+' | tail -1 || true)"PLATFORM_TOKEN="$(printf '%s\n' "$OUT" | grep -oE 'flb_platform_[A-Za-z0-9]+' | tail -1 || true)"+ ORGANIZATION_ID="$(printf '%s\n' "$OUT" | grep -oE 'MINTED_COMPANY_ID=company_[A-Za-z0-9]+' | tail -1 | cut -d= -f2 || true)"if [[ -z "$KEY" ]]; thenecho "::error::Could not mint an API key from the running stack. Tinker output:"printf '%s\n' "$OUT"@@ -68,9 +108,27 @@ runs:fiecho "::add-mask::$KEY"echo "api_key=$KEY" >> "$GITHUB_OUTPUT"- # A few endpoints (organizations listing, driver onboarding) sit behind the- # platform API token rather than an org credential and answer 401 to an- # flb_live_ key. Absent is not fatal — only those requests will 401.+ # The Customers folder is entirely dependent on the seeded verification codes, so+ # fail loudly here rather than leaving 16 requests to fail with an opaque+ # "Invalid verification code provided." The snippet echoes this line last, so its+ # presence also proves the whole snippet ran without throwing.+ SEEDED_CODE="$(printf '%s\n' "$OUT" | grep -oE 'SEEDED_VERIFICATION_CODE=[A-Za-z0-9]+' | tail -1 | cut -d= -f2 || true)"+ if [[ "$SEEDED_CODE" != "$VERIFICATION_CODE" ]]; then+ echo "::error::Customer fixtures were not seeded (expected code '${VERIFICATION_CODE}', got '${SEEDED_CODE}'). Tinker output:"+ printf '%s\n' "$OUT"+ exit 1+ fi+ # Requests that address an organization by path id resolve {{organization_id}}.+ # Absent is not fatal — the collection also chains it from Get Current+ # Organization, so this is belt-and-braces for a partial run.+ if [[ -n "$ORGANIZATION_ID" ]]; then+ echo "organization_id=$ORGANIZATION_ID" >> "$GITHUB_OUTPUT"+ else+ echo "::warning::No organization public_id minted; {{organization_id}} falls back to the collection's chained value."+ fi+ # The organizations listing sits behind the platform API token rather than an+ # org credential and answers 401 to an flb_live_ key. Absent is not fatal —+ # only those requests will 401.if [[ -n "$PLATFORM_TOKEN" ]]; thenecho "::add-mask::$PLATFORM_TOKEN"echo "platform_token=$PLATFORM_TOKEN" >> "$GITHUB_OUTPUT"@@ -113,9 +171,14 @@ runs:env:API_KEY: ${{ steps.key.outputs.api_key }}PLATFORM_TOKEN: ${{ steps.key.outputs.platform_token }}+ ORGANIZATION_ID: ${{ steps.key.outputs.organization_id }}COLLECTIONS: ${{ inputs.collections }}BASE_URL: ${{ inputs.base-url }}NAMESPACE: ${{ inputs.namespace }}+ CUSTOMER_IDENTITY: ${{ inputs.customer-identity }}+ CUSTOMER_PASSWORD: ${{ inputs.customer-password }}+ CUSTOMER_PHONE: ${{ inputs.customer-phone }}+ VERIFICATION_CODE: ${{ inputs.customer-verification-code }}run: |set -uo pipefailoverall=0@@ -135,6 +198,18 @@ runs:# Written with printf, not a heredoc: an unindented heredoc terminator would end# this YAML block scalar.RUNNER="${RUNNER_TEMP:-/tmp}/postman-run.sh"+ # The customer_* / verification_code / push_token vars below are referenced by the+ # Customers folder but declared with no value, and the CLI substitutes only+ # --env-var (see the note further down). Two couplings are deliberate and must not+ # be "tidied up":+ # * customer_email is the SAME value as customer_identity. Update Authenticated+ # Customer mirrors email onto the linked User row+ # (CustomerController::updateMe), so a different value renames the login+ # identity and breaks the Login Customer that the run order defers to the tail.+ # * customer_name matches the literal name in Create a Customer's body, so+ # Update Authenticated Customer is a no-op rename rather than a surprise.+ # verification_code must equal what mint-api-key.php seeded — both read the same+ # action input, so they cannot drift.printf '%s\n' \'#!/usr/bin/env bash' \'postman collection run "$1" \' \@@ -142,6 +217,14 @@ runs:' --env-var "namespace=${NAMESPACE}" \' \' --env-var "api_key=${API_KEY}" \' \' --env-var "platform_token=${PLATFORM_TOKEN}" \' \+ ' --env-var "organization_id=${ORGANIZATION_ID}" \' \+ ' --env-var "customer_identity=${CUSTOMER_IDENTITY}" \' \+ ' --env-var "customer_email=${CUSTOMER_IDENTITY}" \' \+ ' --env-var "customer_name=Jane Customer" \' \+ ' --env-var "customer_password=${CUSTOMER_PASSWORD}" \' \+ ' --env-var "customer_phone=${CUSTOMER_PHONE}" \' \+ ' --env-var "verification_code=${VERIFICATION_CODE}" \' \+ ' --env-var "push_token=ci-contract-push-token" \' \' "${@:2}"' > "$RUNNER"chmod +x "$RUNNER"@@ -178,12 +261,14 @@ runs:# Error: Reporter "json" is not supported for multi-protocol collections.# So the summary below is parsed from the cli reporter's ASCII table.# Run every request explicitly, in the collection's own order but with each- # DELETE moved to the end. The collection is published as API reference- # documentation, so its structure and ordering cannot be changed to suit the- # test run — but a delete that fires mid-run destroys a record the remaining- # requests still need, which is what produced most of the 404s. The CLI- # honours the order of repeated -i flags, so deferring them costs nothing and- # keeps DELETE coverage intact.+ # DELETE — and each explicitly pinned request — moved to the end. The collection+ # is published as API reference documentation, so its structure and ordering+ # cannot be changed to suit the test run — but a delete that fires mid-run+ # destroys a record the remaining requests still need, which is what produced+ # most of the 404s. The same applies to the Customers folder's logout/reset+ # requests, which revoke the Customer-Token the rest of the folder needs; see+ # RUN_LAST in order-collection-requests.py. The CLI honours the order of+ # repeated -i flags, so deferring costs nothing and keeps coverage intact.args=("$dir" -r cli)if [[ -f scripts/ci/order-collection-requests.py ]]; thenwhile IFS= read -r req; do@@ -196,7 +281,10 @@ runs:# The CLI does NOT resolve the collection variables declared in# .resources/definition.yaml — verified: with no --env-var at all, even- # {{base_url}} stays literal. Only --env-var values are substituted. Ledger and+ # {{base_url}} stays literal. Only --env-var values are substituted. This is why+ # the customer_* variables are injected above even though the collection now+ # declares them: the declarations exist for humans importing the collection in+ # the Postman app, and are inert here. Ledger and# Storefront declare api_prefix there, so without this every one of their# requests would go to /%7B%7Bapi_prefix%7D%7D/... and 404. Read it from the# collection rather than hardcoding, so a new prefixed collection just works.diff --git a/scripts/ci/mint-api-key.php b/scripts/ci/mint-api-key.phpindex fa1c4b11..e5b9fbcc 100644--- a/scripts/ci/mint-api-key.php+++ b/scripts/ci/mint-api-key.php@@ -12,6 +12,20 @@// prints the flb_live_ key. The key is generated by ApiCredentialObserver on insert,// so the credential MUST be created through the Eloquent model, then reloaded. The// company must have an owner or the public-API middleware rejects the key (401).+//+// It also prints the organization's public_id, which the collection needs for requests+// that address an organization by id (Onboard, Switch Driver Organization).+//+// Finally it seeds the Customers folder's fixtures. Those requests need a verification+// code, and codes are six random digits delivered only by email/SMS — a collection run+// cannot obtain one unaided. Rather than adding a bypass to the API, we pre-create the+// customer and the exact VerificationCode rows the three code-checking endpoints look+// for. See the CUSTOMER FIXTURES block below.+//+// The four customer values are read from the environment so the action that injects+// {{verification_code}} into the collection run is the single source of truth (it passes+// them with `docker compose exec -e`). The fallbacks below match the action's input+// defaults so this script still works when run by hand for local verification.try {$company = \Fleetbase\Models\Company::firstOrCreate(['name' => 'CI Contract Org']);@@ -41,14 +55,96 @@ try {echo PHP_EOL . 'MINTED_API_KEY=' . $credential->fresh()->key . PHP_EOL;- // A handful of endpoints (organizations listing, driver onboarding) sit behind- // AuthenticatePlatformApiToken rather than an org API credential, and answer 401+ // Feeds the collection's {{organization_id}}. Requests that take an organization in+ // the path expect the public_id (company_xxxxxxxxxx), not the uuid.+ echo 'MINTED_COMPANY_ID=' . $company->public_id . PHP_EOL;++ // The organizations listing (GET /v1/organizations) sits behind+ // AuthenticatePlatformApiToken rather than an org API credential, and answers 401// to an flb_live_ key. Only the hash is persisted, so the plaintext cannot be read// back — rotating is the only way to learn a usable token. Safe here because this// script only ever runs against a throwaway CI stack; do not run it against an// install whose platform token is already in use.$platformToken = \Fleetbase\Support\PlatformApi::rotateToken();echo 'MINTED_PLATFORM_TOKEN=' . $platformToken . PHP_EOL;++ /* ============================================================+ | CUSTOMER FIXTURES (Fleetbase API / Customers)+ * ============================================================ */++ $customerIdentity = getenv('CI_CUSTOMER_IDENTITY') ?: '[email protected]';+ $customerPhone = getenv('CI_CUSTOMER_PHONE') ?: '+15555550123';+ $customerPassword = getenv('CI_CUSTOMER_PASSWORD') ?: 'CiCustomerPassw0rd!';+ $customerCode = getenv('CI_CUSTOMER_VERIFICATION_CODE') ?: '000000';++ // The customer User. Seeding it (rather than letting Request Customer Creation Code+ // create the stub) buys three things the run depends on:+ // * a known password, so Login Customer can authenticate;+ // * a known phone, so Request Customer Login SMS resolves a user instead of+ // 400ing with "No customer with this phone number found";+ // * a stable uuid, so the `fleetops_customer_login` code below can be scoped to+ // the subject that CustomerController::verifyCode looks it up by.+ // Deliberately no Contact row — Create a Customer must still create that itself.+ $customer = \Fleetbase\Models\User::where('email', $customerIdentity)->withoutGlobalScopes()->first();+ if (!$customer) {+ $customer = new \Fleetbase\Models\User();+ $customer->email = $customerIdentity;+ $customer->company_uuid = $company->uuid;+ }+ // Reassert every field on reruns so a mutated row (Update Authenticated Customer+ // rewrites name/email/phone; Reset Customer Password rewrites the password) is+ // restored to the state the collection expects.+ $customer->name = 'Jane Customer';+ $customer->phone = $customerPhone;+ $customer->type = 'customer';+ $customer->status = 'active';+ // `password` is guarded against mass assignment; direct assignment runs the+ // setPasswordAttribute mutator, which hashes it.+ $customer->password = $customerPassword;+ $customer->save();++ // The three VerificationCode rows, one per code-checking endpoint. Each is matched+ // by a different set of columns, so all three are required:+ //+ // for=fleetops_create_customer CustomerController::create matches+ // code + for + meta->identity+ // for=fleetops_customer_login ::verifyCode matches subject_uuid + code + for+ // for=fleetops_customer_password_reset ::resetPassword matches code + for + meta->identity+ //+ // `000000` sits outside VerificationCode's mt_rand(100000, 999999) range, so a seeded+ // code can never collide with a genuine one.+ $seedVerificationCode = function (string $for, array $meta = []) use ($customer, $customerCode) {+ // Clear prior rows for this subject/purpose so reruns are deterministic.+ // ExpiryScope hides expired rows from a normal query, so drop global scopes to+ // be sure leftovers from an earlier run are really gone.+ \Fleetbase\Models\VerificationCode::withoutGlobalScopes()+ ->where(['subject_uuid' => $customer->uuid, 'for' => $for])+ ->delete();++ // generateFor(save: false) sets `for` and the polymorphic subject via+ // HasSubject::setSubject (subject_type is the FQCN).+ $code = \Fleetbase\Models\VerificationCode::generateFor($customer, $for, false);+ $code->expires_at = \Illuminate\Support\Carbon::now()->addDay();+ $code->meta = $meta;+ $code->status = 'active';+ $code->save();++ // VerificationCode::boot() registers a `creating` hook that unconditionally+ // overwrites `code` with mt_rand(100000, 999999), so the known value cannot be+ // set on insert. `creating` does not fire on update — assign and save again.+ $code->code = $customerCode;+ $code->save();++ return $code;+ };++ $seedVerificationCode('fleetops_create_customer', ['identity' => $customerIdentity]);+ $seedVerificationCode('fleetops_customer_login');+ $seedVerificationCode('fleetops_customer_password_reset', ['identity' => $customerIdentity]);++ echo 'SEEDED_CUSTOMER_IDENTITY=' . $customerIdentity . PHP_EOL;+ echo 'SEEDED_CUSTOMER_PHONE=' . $customerPhone . PHP_EOL;+ echo 'SEEDED_VERIFICATION_CODE=' . $customerCode . PHP_EOL;} catch (\Throwable $e) {echo PHP_EOL . 'MINT_ERROR: ' . get_class($e) . ': ' . $e->getMessage() . PHP_EOL;echo $e->getFile() . ':' . $e->getLine() . PHP_EOL;diff --git a/scripts/ci/order-collection-requests.py b/scripts/ci/order-collection-requests.pyindex 274c5edc..d4a42454 100755--- a/scripts/ci/order-collection-requests.py+++ b/scripts/ci/order-collection-requests.py@@ -1,13 +1,61 @@#!/usr/bin/env python3"""Emit `-i <Folder/Request>` args for a Postman git-native collection directory,-in the collection's own order, with every DELETE deferred to the end.+in the collection's own order, with every DELETE — and any explicitly pinned+request — deferred to the end.The collection doubles as published API reference, so its on-disk structure and-ordering must not change. Deferring deletes at run time keeps DELETE coverage-without letting a delete destroy a record the rest of the run still needs.+ordering must not change. Deferring at run time keeps full coverage without+letting one request destroy state the rest of the run still needs.++Two deferral rules, in ascending order of precedence:++ 1. DELETE (heuristic). Any DELETE may strand a later request that reads the+ record, so all of them move to the tail.+ 2. RUN_LAST (explicit). Session teardown cannot be expressed as a heuristic,+ because ordering matters *between* the deferred requests — see below."""import os, re, sys+# Requests relocated to the very end of the run, in exactly the order listed.+# Keyed by collection directory name.+#+# Fleetbase API / Customers issues a Sanctum token (`Customer-Token`) and has+# three requests that destroy it:+#+# * Logout Customer revokes the token used on that request+# * Logout All Customer Sessions revokes every token for the user+# * Reset Customer Password revokes every token as a side effect+# (CustomerController::resetPassword calls+# deleteUserTokens after setting the password)+#+# Deferring all three is not sufficient: whichever logout runs first leaves the+# other holding a dead token, so a fresh token has to be minted in between.+# Login Customer is relocated here to do exactly that — safe to move out of its+# natural position because Create a Customer already bootstraps customer_token+# earlier in the run via its afterResponse script.+#+# Reset Customer Password is a *public* route (no AuthenticateCustomerToken+# middleware) — it needs no token, it only destroys them — so it is free to run+# dead last.+# Request Customer Login SMS is pinned for a different reason: Create a Customer+# sends {{$randomPhoneNumber}}, and creating the customer Contact syncs that phone+# onto the linked User row — so after it runs, User.phone is a random number and+# looking the customer up by the fixed {{customer_phone}} 400s with "No customer+# with this phone number found". Update Authenticated Customer sends+# {{customer_phone}} and mirrors it back onto the User, so this request only+# succeeds once that has run. Pinning it to the head of the tail puts it after+# Update Authenticated Customer (order 9000) while keeping it before the logouts.+# It is a public route, so it needs no token.+RUN_LAST = {+ 'Fleetbase API': [+ 'Customers/Request Customer Login SMS', # needs User.phone restored by Update Me+ 'Customers/Logout Customer', # revokes the current token+ 'Customers/Login Customer', # re-mints customer_token+ 'Customers/Logout All Customer Sessions', # revokes every token+ 'Customers/Reset Customer Password', # public route, no token needed+ ],+}+root = sys.argv[1]def field(path, key, default=None):try:@@ -16,7 +64,11 @@ def field(path, key, default=None):except OSError:return default+# Pinned order for this collection, as {path: index}. Unknown collection => {}.+run_last = {p: i for i, p in enumerate(RUN_LAST.get(os.path.basename(root.rstrip('/')), []))}+items = []+seen = set()for folder in os.listdir(root):d = os.path.join(root, folder)if not os.path.isdir(d) or folder.startswith('.'):@@ -29,7 +81,29 @@ for folder in os.listdir(root):name = fn[:-len('.request.yaml')]method = (field(p, 'method', '?') or '?').upper()rorder = int(field(p, 'order', 10**9))- items.append((method == 'DELETE', forder, folder, rorder, name))+ path = f'{folder}/{name}'+ seen.add(path)+ if path in run_last:+ # Phase 2 sorts after the DELETEs: "pinned last" means last, and+ # explicit intent beats the heuristic. Nothing in Fleetbase API+ # currently deletes the customer's Contact or User, so the relative+ # order of phases 1 and 2 is inert today — but a future RUN_LAST+ # entry that depends on a record a DELETE removes would need this.+ phase, primary, secondary = 2, run_last[path], 0+ sort_folder = ''+ else:+ phase, primary, secondary = (1 if method == 'DELETE' else 0), forder, rorder+ sort_folder = folder+ items.append((phase, primary, sort_folder, secondary, name, path))++for *_key, path in sorted(items):+ print(path)-for _is_delete, _fo, folder, _ro, name in sorted(items):- print(f'{folder}/{name}')+# A rename in the postman repo would silently un-pin a request and quietly+# reintroduce the token-revocation failures. Warn, but do NOT exit non-zero: the+# caller consumes stdout with `while read req; do args+=(-i "$req"); done`, and+# never checks the exit status — so failing here would yield a partial or empty+# -i list, a worse and much less obvious failure than a red annotation.+for path in run_last:+ if path not in seen:+ print(f'::warning::RUN_LAST entry not found in collection: {path}', file=sys.stderr)