Provide reusable authenticated Development browser acceptance fixtures
This commit is contained in:
parent
9133e520fd
commit
299500f92a
12
AGENTS.md
12
AGENTS.md
@ -203,3 +203,15 @@ signing keys. Verify the deployed full commit, perform the brief's live acceptan
|
||||
(including genuine database persistence/reload), then record receipt, tests, feature
|
||||
URL and factual effort in CYJ before completion. Reconcile uncertain deployment
|
||||
outcomes before retrying. Production remains separately authorised.
|
||||
|
||||
## Authenticated Development browser acceptance
|
||||
|
||||
Use `Docs/Codex/BrowserAcceptance.md` and `Tools/BrowserAcceptance/run.py` for the
|
||||
permanent Application-only Development writer identity. Import the reusable
|
||||
`PlotLine.Tests/Browser/dev-acceptance.cjs` helper; authenticate normally, create a
|
||||
unique registered disposable project, test actual UI and server persistence after
|
||||
reload/fresh login, then clean up via the ordinary scoped project lifecycle. Never
|
||||
print credentials, record login traces/storageState, target Production or use SQL/
|
||||
sudo for routine browser fixtures. Preserve pending run journals and use documented
|
||||
resume cleanup on failure. Report deployed commit, URLs, actual checks, cleanup and
|
||||
limitations in CYJ; task-specific acceptance must still be performed by its worker.
|
||||
|
||||
182
Docs/Codex/BrowserAcceptance.md
Normal file
182
Docs/Codex/BrowserAcceptance.md
Normal file
@ -0,0 +1,182 @@
|
||||
# Unattended authenticated Development acceptance
|
||||
|
||||
The Application worker has a permanent dedicated ordinary writer identity in
|
||||
`PlotDirector_Development`. It owns only synthetic fixtures; it has no administrator
|
||||
access, personal project memberships or Production account. Runtime authentication,
|
||||
email confirmation and optional MFA policies are unchanged. Sessions use normal
|
||||
antiforgery-protected login. No cookies are forged and no authentication endpoint,
|
||||
application backdoor or schema change was added.
|
||||
|
||||
## Routine worker session
|
||||
|
||||
From `/srv/repos/PlotDirector`, write a task-specific Node script importing:
|
||||
|
||||
```js
|
||||
const {open} = require('/srv/repos/PlotDirector/PlotLine.Tests/Browser/dev-acceptance.cjs');
|
||||
let session;
|
||||
(async () => {
|
||||
try {
|
||||
session = await open();
|
||||
const project = await session.project();
|
||||
const book = await session.create('Books', '?projectId=' + project,
|
||||
{BookTitle: 'Disposable acceptance book', BookNumber: 1});
|
||||
// Exercise the actual affected UI using session.page and relative session.goto.
|
||||
// Save through normal forms, reload and verify saved values. Open a fresh
|
||||
// session under this same lock when stronger persistence evidence is needed.
|
||||
} finally {
|
||||
if (session) {
|
||||
try { await session.cleanup(); }
|
||||
finally { await session.close(); }
|
||||
}
|
||||
}
|
||||
})().catch(() => {
|
||||
console.error('Acceptance failed; preserve run state and request assistance. No credentials logged.');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
```
|
||||
|
||||
Launch it through the account's OS-held lock:
|
||||
|
||||
```sh
|
||||
python3 Tools/BrowserAcceptance/run.py /absolute/path/to/acceptance-script.cjs
|
||||
```
|
||||
|
||||
The controller grants only Application access to the private browser credential.
|
||||
The launcher/session require the Application worker when invoked by a controller.
|
||||
No sudo, runtime configuration, deployment keys or database login is needed.
|
||||
Session startup rejects unexpected project memberships without opening their contents.
|
||||
Do not invite this identity into personal projects. A second session fails promptly while the first holds the lock. Keep the entire
|
||||
fixture lifecycle inside the launcher; opening two browser contexts serially within
|
||||
one run is supported. Do not run independent sessions against this identity.
|
||||
|
||||
These sessions are online incognito browsers with service workers disabled so saved
|
||||
state is read from the server. Existing offline/installed-PWA specialist workflows
|
||||
need their own reviewed coverage.
|
||||
|
||||
The helper reads `~/.config/cyj/credentials/application-browser.json` directly in
|
||||
process (owner 0600; parent 0700). Never print/cat it, put values in environment
|
||||
variables/arguments, paste them into a prompt/CYJ, or retain login screenshots,
|
||||
Playwright traces, HAR, videos, storageState, cookie exports or raw authentication
|
||||
errors. The launcher removes inherited Playwright/Chromium debug/trace settings that could
|
||||
log password input. The helper returns the authenticated page, not credential values. Use safe
|
||||
stage/check summaries on failure; raw Playwright exceptions may include form values.
|
||||
|
||||
Its browser requests are pinned to `https://dev.plotdirector.com`. Only the exact
|
||||
Chart.js and SignalR script URLs already pinned in `_Layout` may load externally,
|
||||
as GET script resources. Production, HTTP and other external requests are blocked
|
||||
before network access. Do not remove the route guard, use `context.request`/raw
|
||||
APIRequestContext (which bypass browser routes), or override the target. The testing
|
||||
identity is provisioned only in Development; no Production identity is created.
|
||||
|
||||
## Fixture lifecycle and persistence
|
||||
|
||||
`session.project()` registers a unique `CYJ acceptance <32-character run ID>` project
|
||||
before submitting its real form. Use that project as the root for all test data.
|
||||
`session.create(area, query, fields, prepare?)` supports ordinary record forms for
|
||||
Books, Chapters, Characters, Locations, StoryAssets, PlotLines and PlotThreads.
|
||||
The optional async `prepare(page)` callback handles conditional controls, for example
|
||||
filling CustomSex only when its input is enabled and required. Standard browser
|
||||
validation runs before native `requestSubmit`; server validation and antiforgery
|
||||
remain intact. Fixture creation does not certify pointer/keyboard interaction:
|
||||
exercise the actual affected controls explicitly in task acceptance.
|
||||
|
||||
Scenes, character relationships and Timeline operations use the existing normal
|
||||
application UI and endpoints through the authenticated `session.page`, `goto` and
|
||||
`post` helpers. `post(relativeRoute, fields)` uses same-origin browser fetch with
|
||||
an actual antiforgery token from the current page; it has no SQL or privileged path.
|
||||
Follow the real form's fields/options. Do not invent lookup IDs, create standalone
|
||||
records in unrelated projects, use repository SQL fixtures, run AI analysis/imports
|
||||
unnecessarily, add collaborators or change authentication/billing settings.
|
||||
|
||||
Verify a saved edit after navigating away and reloading, then preferably close the
|
||||
browser and `open()` a fresh authenticated session under the same launcher/run ID.
|
||||
Read the actual server-rendered values. Do not stub mutation responses or count a
|
||||
successful HTTP status/toast/DOM change as persistence evidence. Record the tested
|
||||
commit, URLs, real checks, fixture cleanup and limitations in CYJ. No unsupported
|
||||
acceptance criterion may be marked complete.
|
||||
|
||||
`cleanup()` uses the normal archive and owner-confirmed permanent project deletion
|
||||
workflow. It checks the recorded exact random project name, uses only that run's
|
||||
registered IDs, and confirms absence from both active/archived cards and Details.
|
||||
It never deletes the persistent identity or other projects/accounts. Project deletion
|
||||
removes its owned books, chapters, scenes, characters, locations and associated data
|
||||
through the existing application lifecycle. Never use direct SQL cleanup.
|
||||
|
||||
Run journals are private 0600 files in `~/.local/state/cyj/browser/application/`.
|
||||
If a run crashes, the kernel releases its lock; pending fixtures block a fresh run.
|
||||
Inspect only the non-secret journal for its run ID and resume cleanup explicitly:
|
||||
|
||||
```sh
|
||||
python3 Tools/BrowserAcceptance/run.py --resume RUN_ID \
|
||||
PlotLine.Tests/Browser/dev-acceptance-cleanup.cjs
|
||||
```
|
||||
|
||||
Interrupted project creation can be recovered by its exact random name. Cleanup
|
||||
failures preserve the journal. Request assistance rather than deleting the journal,
|
||||
forcing locks, guessing IDs, weakening permissions or using arbitrary SQL. The
|
||||
permanent account remains ready after successful fixture cleanup.
|
||||
|
||||
## One-time operator provisioning and recovery
|
||||
|
||||
These commands run outside the unattended sandbox. Routine tests never invoke them.
|
||||
Read [database operations](Database.md) before provisioning.
|
||||
|
||||
1. Run the existing test-only operational helper:
|
||||
`dotnet run --project PlotLine.Tests -- --dev-browser-identity create /tmp/pd-dev-browser-UNIQUE.json`.
|
||||
It verifies Atlas, the fixed SQL endpoint and actual Development database; takes
|
||||
and verifies a COPY_ONLY/CHECKSUM backup through the installed Development worker;
|
||||
uses normal User_Create/password hashing and verification-token confirmation;
|
||||
and writes a new private credential file. No deployment/service restart occurs.
|
||||
The runtime SQL principal remains unable to back up databases. The backup worker
|
||||
verifies the currently active signed package and uses the existing OS/SQL locks,
|
||||
schema/history and idle checks. It neither migrates nor records a new release.
|
||||
2. Run `python3 Tools/BrowserAcceptance/install_identity.py /tmp/pd-dev-browser-UNIQUE.json`.
|
||||
It installs the fixed private credential file exclusively and removes the staging
|
||||
copy. An existing permanent identity is never silently replaced.
|
||||
3. Run `dotnet run --project PlotLine.Tests -- --dev-browser-identity configure-worker ~/.config/cyj/credentials/application-browser.json`.
|
||||
After another verified backup, this verifies the exact fixture credentials and
|
||||
grants the existing audited non-expiring administrative entitlement override at
|
||||
the account's current ordinary writer plan. It does not grant Administrator access,
|
||||
alter Stripe or bypass authentication. The single configured confirmed human
|
||||
administrator supplies the audit sponsor; multiple/missing configured administrators
|
||||
fail closed for operator review. This prevents the default trial expiring later.
|
||||
4. Root-owned `/etc/cyj/development-deployments.json` declares the Application entry's
|
||||
`worker_private_files` containing that credential path. Only this worker gets read
|
||||
access; all other registered workers receive exact deny-read rules. The file must
|
||||
be a regular, owner-only 0600 file with one link. Add only
|
||||
`~/.local/state/cyj/browser/application` to Application writable directories.
|
||||
Drain/stop the controller before installing configuration and restart afterward.
|
||||
No blanket sudo, sandbox bypass or browser credential grant to Website is needed.
|
||||
|
||||
If normal MFA is enabled for this identity later, do not disable/bypass it to make a
|
||||
test pass. The current helper fails closed at login; request approved fixture/MFA
|
||||
maintenance. Password/lockout/credential recovery is an operator operation, not a
|
||||
new test account per session. Normal plan quotas still apply; keep one disposable
|
||||
project/run and clean it up. The administrative override is Development-only.
|
||||
|
||||
## Qualification
|
||||
|
||||
Focused offline gates:
|
||||
|
||||
```sh
|
||||
node --test PlotLine.Tests/Browser/dev-acceptance.test.cjs
|
||||
python3 -m unittest discover -s Tools/BrowserAcceptance -v
|
||||
```
|
||||
|
||||
The shared toolkit's `scripts/check-development-browser.py` runs the real configured
|
||||
Codex sandbox/profile from a transient user-systemd service, with no inference,
|
||||
CYJ writes, task claim or deployment. Its live probe authenticates, tests read/write
|
||||
isolation using an unrelated disposable identity's non-secret project/book IDs,
|
||||
checks administrator denial and Production request blocking, creates ordinary
|
||||
fixtures, saves/reloads in a fresh browser, and permanently cleans its own project.
|
||||
The unrelated sentinel is operator-provisioned with the existing helper and removed
|
||||
through that helper's normal complete account deletion afterward. Its credentials
|
||||
remain in a deployment-private directory denied to workers. Do not use personal
|
||||
manuscripts as security fixtures.
|
||||
|
||||
The probe reads `sentinel-ids.json` from the private browser state directory and
|
||||
writes only a safe `capability-verification.json`. It is installation qualification,
|
||||
not a substitute for task-specific acceptance. A separate `--worker website
|
||||
--deny-read` probe checks the actual filesystem denial without loading Website CYJ
|
||||
credentials or reading any browser credential bytes. See the shared toolkit's
|
||||
`BROWSER-ACCEPTANCE.md` for invocation and installation details.
|
||||
@ -50,3 +50,11 @@ For changes affecting `PlotDirector.WordCompanion`, use its npm workflow:
|
||||
This generates and validates the manifest for the application-hosted `/word-companion` route.
|
||||
|
||||
Do not run Word Companion validation for unrelated application changes merely for completeness.
|
||||
|
||||
## Authenticated unattended Development acceptance
|
||||
|
||||
Use [BrowserAcceptance.md](BrowserAcceptance.md) for the permanent isolated writer
|
||||
identity, locked ordinary Playwright sessions, fixture lifecycle, persistence/reload
|
||||
checks and scoped cleanup. Routine workers need neither sudo nor SQL credentials.
|
||||
The existing `DevBrowserIdentity` command is now operator-only provisioning/recovery;
|
||||
its backup reuses the installed Development worker because runtime SQL cannot back up.
|
||||
|
||||
140
Docs/Deployment/AuthenticatedAcceptance-20261129.md
Normal file
140
Docs/Deployment/AuthenticatedAcceptance-20261129.md
Normal file
@ -0,0 +1,140 @@
|
||||
# Authenticated unattended Development acceptance — 29 November 2026
|
||||
|
||||
The Application worker now has a permanent isolated ordinary writer identity and
|
||||
reusable authenticated browser/fixture tooling. No web application authentication
|
||||
change, new authentication service, privileged worker command or deployment was
|
||||
needed. The current Timeline implementation was not repeated or redeployed.
|
||||
|
||||
The existing DevBrowserIdentity helper, user/password/email-verification repositories,
|
||||
normal antiforgery login, Playwright installation, account storage conventions,
|
||||
project archive/permanent-delete workflow, deployment backup worker and administrative
|
||||
entitlement override were reused. The old helper's runtime-SQL backup failed before
|
||||
account creation because that principal correctly lacks BACKUP DATABASE. Operator
|
||||
setup now reuses the installed Development worker's verified active package, locks,
|
||||
schema/history/idle checks and COPY_ONLY/CHECKSUM/VERIFYONLY backup. Runtime SQL
|
||||
permissions were not broadened. Operator errors are handled without raw exception
|
||||
output or unhandled-exception dumps; crash-report roots are denied to workers.
|
||||
|
||||
The permanent identity was created only in `PlotDirector_Development`, confirmed
|
||||
through the existing verification-token workflow, and given the same ordinary writer
|
||||
plan through the existing audited non-expiring administrative override. The configured
|
||||
confirmed administrator is the audit sponsor; this does not grant Administrator
|
||||
access, change Stripe or weaken MFA/authentication. A future-dated lookup confirms
|
||||
continued entitlement after trial expiry. A setup retry confirmed no additional write.
|
||||
|
||||
Credentials are random, private owner 0600 data under the existing CYJ 0700 credential
|
||||
directory, outside source control. Root-owned policy grants Application read-only
|
||||
access and denies every other worker and evaluation-only execution. Protected
|
||||
operational secret roots cannot be delegated through that setting. Routine tests
|
||||
receive no SQL, runtime, deployment or signing credentials and use no sudo. No
|
||||
credential values, cookies, login traces, storageState or authentication responses
|
||||
are recorded in reports or CYJ.
|
||||
|
||||
## Reusable workflow and isolation
|
||||
|
||||
[BrowserAcceptance.md](../Codex/BrowserAcceptance.md) documents:
|
||||
|
||||
- `Tools/BrowserAcceptance/run.py`: OS-held account lock and durable per-run journal.
|
||||
- `dev-acceptance.cjs`: normal authenticated Development session, unique registered
|
||||
disposable project, ordinary record forms and conditional field preparation.
|
||||
- Real UI testing, server-backed reload and fresh-browser persistence verification.
|
||||
- Owner-checked archive and permanent project deletion, confirming absence from
|
||||
both active/archived cards and Details. The permanent identity is retained.
|
||||
- Interrupted-create recovery by exact random project name, and explicit locked
|
||||
`--resume RUN_ID` cleanup. Pending fixtures prevent a new independent session.
|
||||
|
||||
All test data belongs under that run's registered project. Session startup refuses
|
||||
unexpected project memberships without opening their contents. Do not invite this
|
||||
identity into personal projects. If testing project renaming, restore its exact
|
||||
registered random name before cleanup. Scenes, relationships, locations, Timeline
|
||||
and other ordinary writer controls use their existing application UI/endpoints;
|
||||
no SQL fixture API or unrestricted cleanup mechanism was added.
|
||||
|
||||
The browser origin is fixed to HTTPS Development. Only the application's two exact
|
||||
pinned Chart.js/SignalR GET script resources are allowed externally. Production and
|
||||
other external browser requests are aborted before network access. Do not bypass
|
||||
this guard using raw APIRequestContext or remove routes. Normal application
|
||||
permission checks remain authoritative; the dedicated identity has no personal
|
||||
memberships and never receives another user's session.
|
||||
|
||||
## Verification through the unattended boundary
|
||||
|
||||
The actual configured Codex sandbox/profile ran from a transient user-systemd
|
||||
service with real credentials, real application and database persistence. No model
|
||||
inference, fake authentication, CYJ writes/claims or deployment was used.
|
||||
[Safe qualification evidence](Evidence/AuthenticatedAcceptance-20261129/verification.json)
|
||||
records eleven passing checks:
|
||||
|
||||
1. no_new_privs remains enabled.
|
||||
2. Runtime configuration and signing key cannot be opened.
|
||||
3. Normal browser authentication succeeds.
|
||||
4. The dedicated workspace is initially empty and isolated.
|
||||
5. Another disposable account's project/book reads and project write return 404.
|
||||
6. Administrator access is denied.
|
||||
7. A Production request is intercepted and aborted before network.
|
||||
8. Ordinary project/book/chapter/character/location forms create disposable data.
|
||||
9. A changed book title survives normal save, navigation and reload.
|
||||
10. A fresh authenticated browser reads the same persisted server value.
|
||||
11. Normal owner-confirmed permanent cleanup removes the fixture project.
|
||||
|
||||
A separate real Website sandbox profile cannot open the Application browser credential;
|
||||
that probe reads no credential bytes and loads no Website CYJ credentials. The
|
||||
unrelated sentinel owner separately verified its data remained unchanged, then the
|
||||
existing complete account-deletion helper removed that temporary identity and all
|
||||
its projects/books. The persistent Application identity remains with no pending
|
||||
fixture projects. No personal manuscripts were used or modified.
|
||||
|
||||
The fixture helper uses native form requestSubmit with normal client/server validation
|
||||
and antiforgery. This permits repeatable setup when desktop controls obscure a Save
|
||||
button; it does not certify pointer/keyboard UX. Task-specific acceptance must still
|
||||
exercise the actual affected controls. Conditional required fields are supplied as
|
||||
synthetic fixture data, never by bypassing validation.
|
||||
|
||||
Gates passed: `dotnet build PlotLine.slnx` (zero warnings/errors); all 897 executable
|
||||
regression checks; four Node security tests; two Python concurrency/recovery tests;
|
||||
89 toolkit tests with one native Windows-only skip; nine existing Development
|
||||
profile boundary tests; process-tree containment and the generic Codex sandbox probe.
|
||||
|
||||
## Installed state and recovery
|
||||
|
||||
The shared toolkit is version 1.3.1, commit `775ba98b6cadb590f62841c3e36a4331409d4104`. Its controller private-file policy and
|
||||
Application-only browser run-state writable path are installed. Controller polling
|
||||
was drained/stopped for maintenance and restored afterward. No application service
|
||||
restart, SQL schema migration, new sudo rule or Production operation occurred.
|
||||
Repository AGENTS.md, Testing/Browser guides and shared worker/controller/installation
|
||||
instructions describe the permanent workflow and failure recovery.
|
||||
|
||||
Routine tests need no operator or human login. Normal plan quotas still apply.
|
||||
If MFA is deliberately enabled later, or credentials/lockout/administrator policy
|
||||
change, the helper fails closed for approved maintenance; do not disable protection.
|
||||
These sessions are online incognito browsers with service workers disabled; offline
|
||||
and installed-PWA qualification remains a specialist workflow. Other external services
|
||||
need explicitly reviewed test support. The current work
|
||||
qualifies reusable authentication and fixture persistence, not Timeline-specific UX.
|
||||
|
||||
Development health still reports:
|
||||
|
||||
- Commit `b5672f20b5bb2cd22f31a486f6269cb3eaea28cf`.
|
||||
- Environment `Development`; database `PlotDirector_Development`; healthy `true`.
|
||||
- Existing release `development-b5672f20b5bb-20261129T200058Z`.
|
||||
- Existing authoritative receipt `20261129T200429Z-a5af276f37e4`.
|
||||
|
||||
Task 52 remains InProgress and blocked by open assistance **54**. Neither was
|
||||
modified. There are no remaining technical setup blockers to the original worker's
|
||||
resumption through Clara's normal assistance response/evaluation and fresh claim.
|
||||
It must still perform all Timeline-specific live acceptance and record its own
|
||||
results/completion. No redeployment is required for this testing capability.
|
||||
|
||||
## Non-secret response for Clara
|
||||
|
||||
> The permanent Application Development browser testing capability is operational.
|
||||
> Read `/srv/repos/PlotDirector/Docs/Codex/BrowserAcceptance.md`. Use
|
||||
> `python3 Tools/BrowserAcceptance/run.py /absolute/task-specific-script.cjs` and
|
||||
> import `PlotLine.Tests/Browser/dev-acceptance.cjs` for normal private authentication,
|
||||
> locked disposable fixtures and scoped cleanup. Credentials are already installed;
|
||||
> do not request or publish them and do not run operator provisioning. Keep the
|
||||
> existing deployed `b5672f20…` release; do not redeploy or repeat implementation.
|
||||
> After normal assistance evaluation and a fresh controller-owned claim, perform
|
||||
> task 52's genuine Timeline interactions, persistence/reload checks and cleanup,
|
||||
> then record the deployed commit, receipt, checks, accessible feature URL and factual
|
||||
> effort before completion. Installation qualification does not complete task 52.
|
||||
@ -0,0 +1,53 @@
|
||||
{
|
||||
"passed": true,
|
||||
"stage": "cleanup",
|
||||
"checks": [
|
||||
"native-sandbox-no-new-privileges",
|
||||
"runtime-configuration-and-signing-key-unreadable",
|
||||
"normal-authentication",
|
||||
"isolated-account-empty-workspace",
|
||||
"unrelated-disposable-project-read-and-write-denied",
|
||||
"ordinary-account-not-administrator",
|
||||
"production-request-aborted-before-network",
|
||||
"ordinary-project-book-chapter-character-location-forms",
|
||||
"save-and-reload-persistence",
|
||||
"fresh-authenticated-browser-confirms-server-persistence",
|
||||
"owned-fixture-archived-permanently-deleted-and-absence-verified"
|
||||
],
|
||||
"credentialsLogged": false,
|
||||
"productionContacted": false,
|
||||
"timelineAcceptancePerformed": false,
|
||||
"runtime": {
|
||||
"sourceCommit": "b5672f20b5bb2cd22f31a486f6269cb3eaea28cf",
|
||||
"environment": "Development",
|
||||
"database": "PlotDirector_Development",
|
||||
"healthy": true
|
||||
},
|
||||
"other_worker_credential_open_denied": true,
|
||||
"sentinel_owner_verified_unchanged": true,
|
||||
"temporary_sentinel_identity_and_all_owned_data_removed": true,
|
||||
"pending_fixture_runs": 0,
|
||||
"permanent_identity_retained": true,
|
||||
"permanent_entitlement": "existing audited non-expiring override at current writer plan",
|
||||
"entitlement_future_lookup_verified": true,
|
||||
"entitlement_setup_retry_made_no_changes": true,
|
||||
"real_cyj_writes": 0,
|
||||
"real_deployments": 0,
|
||||
"existing_release": "development-b5672f20b5bb-20261129T200058Z",
|
||||
"existing_deployment_receipt": "20261129T200429Z-a5af276f37e4",
|
||||
"toolkit_version": "1.3.1",
|
||||
"toolkit_commit": "775ba98b6cadb590f62841c3e36a4331409d4104",
|
||||
"toolkit_archive_sha256": "0e8b824de5160be2dca168a69893dd8c7e0bef8f96c574efde9e2340b5995070",
|
||||
"regressions": {
|
||||
"solution_build": "passed; 0 warnings, 0 errors",
|
||||
"application_harness_passed_checks": 897,
|
||||
"node_security_tests": 4,
|
||||
"python_lock_recovery_tests": 2,
|
||||
"toolkit_tests": 89,
|
||||
"toolkit_windows_only_skips": 1,
|
||||
"development_profile_tests": 9,
|
||||
"process_containment": "passed",
|
||||
"generic_codex_sandbox": "passed",
|
||||
"final_ordinary_sandbox_session_without_sentinel": "passed"
|
||||
}
|
||||
}
|
||||
@ -77,3 +77,12 @@ Responsive Chapters, Timeline and Plot Lines: start the isolated Razor host from
|
||||
## Alternative Scenario theme acceptance
|
||||
|
||||
Start the isolated Razor host from the repository root with `dotnet run --project PlotLine.Tests -- --toolbar-browser-host`, then run `xvfb-run -a node PlotLine.Tests/Browser/scenario-themes.cjs` in another terminal. This renders the actual Scenario list, creation, board and Compare views without database access. The test enumerates the configured themes, switches them with the account theme picker, checks populated and empty states at 1440/650 widths, measures representative text contrast, and installs and launches a real standalone Chromium PWA. Screenshots go to `/tmp/pd-scenario-visual` (override with `PD_SCENARIO_SCREENSHOTS`). Movement form identities and chapter selection are checked; database-backed scene movement and applying a scenario are deliberately outside this fixture.
|
||||
|
||||
## Reusable unattended authenticated Development tests
|
||||
|
||||
The permanent dedicated writer identity and `dev-acceptance.cjs` session/fixture
|
||||
helper are documented in [BrowserAcceptance.md](../../Docs/Codex/BrowserAcceptance.md).
|
||||
Launch scripts with `python3 Tools/BrowserAcceptance/run.py SCRIPT` from the repository
|
||||
root. The account lock, run journal and normal project cleanup replace per-test
|
||||
operator provisioning. No sudo or database credentials enter routine sessions.
|
||||
Run the focused helper regressions with `node --test dev-acceptance.test.cjs`.
|
||||
|
||||
2
PlotLine.Tests/Browser/dev-acceptance-cleanup.cjs
Normal file
2
PlotLine.Tests/Browser/dev-acceptance-cleanup.cjs
Normal file
@ -0,0 +1,2 @@
|
||||
const {open}=require('./dev-acceptance.cjs');
|
||||
(async()=>{let session;try{session=await open();await session.cleanup();console.log(JSON.stringify({passed:true,runId:session.runId,cleanup:true}));}finally{if(session)await session.close();}})().catch(()=>{console.error('Dedicated fixture cleanup failed; preserve the run state and request assistance. No credentials logged.');process.exitCode=1;});
|
||||
41
PlotLine.Tests/Browser/dev-acceptance-probe.cjs
Normal file
41
PlotLine.Tests/Browser/dev-acceptance-probe.cjs
Normal file
@ -0,0 +1,41 @@
|
||||
// Generic capability qualification. Timeline-specific acceptance belongs to task 52.
|
||||
const assert=require('node:assert/strict'),fs=require('node:fs');
|
||||
const {open,target}=require('./dev-acceptance.cjs');
|
||||
let stage='session',session,passed=false,failure;const checks=[];
|
||||
(async()=>{try{
|
||||
assert.match(fs.readFileSync('/proc/self/status','utf8'),/^NoNewPrivs:\s+1$/m);checks.push('native-sandbox-no-new-privileges');
|
||||
for(const file of ['/etc/plotdirector/plotdirector.env','/home/nick/.local/share/plotdirector-development/signing/private.pem']){let fd;try{fd=fs.openSync(file,'r');}catch(error){assert(['EACCES','EPERM','ENOENT'].includes(error.code));continue;}fs.closeSync(fd);throw new Error('Protected operational file unexpectedly readable');}
|
||||
checks.push('runtime-configuration-and-signing-key-unreadable');
|
||||
session=await open();checks.push('normal-authentication');
|
||||
await session.goto('/Projects');assert.equal(await session.page.locator('.project-card').count(),0);checks.push('isolated-account-empty-workspace');
|
||||
const sentinel=JSON.parse(process.env.PD_BROWSER_SENTINEL_IDS||'{}');assert(Number.isSafeInteger(sentinel.project)&&Number.isSafeInteger(sentinel.book),'operator-created disposable isolation sentinel required');
|
||||
for(const route of ['/Projects/Details/'+sentinel.project,'/Books/Edit/'+sentinel.book])assert.equal((await session.goto(route)).status(),404);
|
||||
await session.goto('/Projects');
|
||||
const denied=await session.page.evaluate(async id=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;return (await fetch('/Projects/Archive/'+id,{method:'POST',body:new URLSearchParams({__RequestVerificationToken:token})})).status;},sentinel.project);
|
||||
assert.equal(denied,404);checks.push('unrelated-disposable-project-read-and-write-denied');
|
||||
const admin=await session.goto('/Admin');assert(admin.status()===403||new URL(session.page.url()).pathname==='/Account/AccessDenied');checks.push('ordinary-account-not-administrator');
|
||||
assert.throws(()=>target('https://app.plotdirector.com/Projects'));
|
||||
await session.goto('/Projects');const before=session.blockedExternal();
|
||||
assert(await session.page.evaluate(async()=>{try{await fetch('https://app.plotdirector.com/Account/Login',{method:'POST',body:'synthetic-boundary-probe'});return false;}catch{return true;}}));
|
||||
assert(session.blockedExternal()>before);checks.push('production-request-aborted-before-network');
|
||||
stage='create';const project=await session.project();
|
||||
stage='create-book';const book=await session.create('Books','?projectId='+project,{BookTitle:'Disposable acceptance book',BookNumber:1});
|
||||
stage='create-chapter';const chapter=await session.create('Chapters','?bookId='+book,{ChapterTitle:'Disposable chapter',ChapterNumber:1});
|
||||
stage='create-character';await session.create('Characters','?projectId='+project,{CharacterName:'Disposable character'},async page=>{const sex=page.locator('[name=CustomSex]');if(await sex.isEnabled()&&await sex.getAttribute('required')!==null)await sex.fill('Unspecified');});
|
||||
stage='create-location';await session.create('Locations','?projectId='+project,{LocationName:'Disposable location'});
|
||||
checks.push('ordinary-project-book-chapter-character-location-forms');
|
||||
stage='save';await session.goto('/Books/Edit/'+book);
|
||||
const title='Persisted acceptance '+session.runId;
|
||||
await session.page.locator('[name=BookTitle]').fill(title);
|
||||
await Promise.all([session.page.waitForURL('**/Books/Details/'+book),session.page.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).evaluate(button=>button.form.requestSubmit(button))]);
|
||||
await session.goto('/Books/Edit/'+book);await session.page.reload();assert.equal(await session.page.inputValue('[name=BookTitle]'),title);checks.push('save-and-reload-persistence');
|
||||
stage='fresh-session';await session.close();session=await open();await session.goto('/Books/Edit/'+book);assert.equal(await session.page.inputValue('[name=BookTitle]'),title);checks.push('fresh-authenticated-browser-confirms-server-persistence');
|
||||
stage='cleanup';await session.cleanup();await session.goto('/Projects');assert.equal(await session.page.locator('.project-card').count(),0);checks.push('owned-fixture-archived-permanently-deleted-and-absence-verified');
|
||||
passed=true;
|
||||
}catch(error){failure=error.message.startsWith('fixture-create:')?JSON.parse(error.message.slice('fixture-create:'.length)):{type:error.name};throw new Error('Capability check failed');}finally{
|
||||
if(session){try{await session.cleanup();}catch{passed=false;checks.push('cleanup-requires-resume');}await session.close();}
|
||||
const result={passed,stage,failure,checks,credentialsLogged:false,productionContacted:false,timelineAcceptancePerformed:false};
|
||||
if(process.env.PD_BROWSER_EVIDENCE)fs.writeFileSync(process.env.PD_BROWSER_EVIDENCE,JSON.stringify(result,null,2)+'\n',{mode:0o600});
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
})().catch(()=>{console.error('Development capability probe failed at '+stage+'; inspect fixture state and use cleanup recovery. No credentials logged.');process.exitCode=1;});
|
||||
95
PlotLine.Tests/Browser/dev-acceptance.cjs
Normal file
95
PlotLine.Tests/Browser/dev-acceptance.cjs
Normal file
@ -0,0 +1,95 @@
|
||||
// Reusable real Development sessions. Test executable/browser tooling only; never deployed.
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto');
|
||||
const {chromium}=require('playwright');
|
||||
const BASE='https://dev.plotdirector.com';
|
||||
const STATIC_SCRIPTS=new Set(['https://cdn.jsdelivr.net/npm/chart.js@4.4.9/dist/chart.umd.min.js','https://cdn.jsdelivr.net/npm/@microsoft/signalr@8.0.7/dist/browser/signalr.min.js']);
|
||||
function requestAllowed(url,method='GET',type='document'){try{return new URL(url).origin===BASE||(method==='GET'&&type==='script'&&STATIC_SCRIPTS.has(url));}catch{return false;}}
|
||||
const IDENTITY=path.join(os.homedir(),'.config/cyj/credentials/application-browser.json');
|
||||
function check(condition,message){if(!condition)throw new Error(message);}
|
||||
function target(route){check(typeof route==='string'&&route.startsWith('/')&&!route.startsWith('//'),'Only Development-relative routes are supported');const url=new URL(route,BASE);check(url.origin===BASE,'Only Development is permitted');return url.href;}
|
||||
function workspaceAllowed(cards,projects){return cards.every(card=>projects.some(record=>(record.id===card.id||record.id===null)&&record.name===card.name));}
|
||||
function loadIdentity(file=IDENTITY){
|
||||
const parent=fs.lstatSync(path.dirname(file));check(parent.isDirectory()&&!parent.isSymbolicLink()&&parent.uid===process.getuid()&&(parent.mode&0o777)===0o700,'Private credential directory required');
|
||||
const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
|
||||
try{const st=fs.fstatSync(fd);check(st.isFile()&&st.uid===process.getuid()&&(st.mode&0o777)===0o600&&st.nlink===1&&st.size<16384,'Private credential file required');
|
||||
let i;try{i=JSON.parse(fs.readFileSync(fd,'utf8'));}catch{throw new Error('Private credential record is invalid; no contents logged');}
|
||||
check(i.Database==='PlotDirector_Development'&&i.Origin===BASE&&i.Worker==='application'&&i.Purpose==='CYJ Development browser acceptance','Dedicated Development identity required');
|
||||
check(Number.isSafeInteger(i.UserID)&&i.UserID>0&&/^pwa-browser-[a-f0-9]{32}@example\.invalid$/.test(i.Email)&&typeof i.Password==='string'&&i.Password.length>=40,'Invalid dedicated identity');return i;
|
||||
}finally{fs.closeSync(fd);}
|
||||
}
|
||||
function runState(){
|
||||
const id=process.env.PD_DEV_BROWSER_RUN_ID,fd=Number(process.env.PD_DEV_BROWSER_LOCK_FD),file=process.env.PD_DEV_BROWSER_STATE;
|
||||
check(/^[a-f0-9]{32}$/.test(id||'')&&Number.isInteger(fd)&&fd>=3,'Use Tools/BrowserAcceptance/run.py');
|
||||
const text=Buffer.alloc(32);check(fs.readSync(fd,text,0,32,0)===32&&text.toString()===id,'Acceptance lock mismatch');
|
||||
check(file===path.join(os.homedir(),'.local/state/cyj/browser/application',id+'.json'),'Invalid run state path');
|
||||
let state={runId:id,projects:[]};if(fs.existsSync(file)){check(!fs.lstatSync(file).isSymbolicLink(),'Linked state refused');state=JSON.parse(fs.readFileSync(file));check(state.runId===id&&Array.isArray(state.projects),'Invalid run state');}
|
||||
return {id,state,save(){const temporary=file+'.'+crypto.randomUUID();fs.writeFileSync(temporary,JSON.stringify(state),{mode:0o600,flag:'wx'});fs.renameSync(temporary,file);}};
|
||||
}
|
||||
async function login(page,identity){
|
||||
try{check((await page.goto(target('/Account/Login'))).status()===200,'Login unavailable');
|
||||
await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);
|
||||
await Promise.all([page.waitForURL(BASE+'/Projects'),page.locator('form button[type=submit]').click()]);
|
||||
}catch{throw new Error('Normal Development login failed; check fixture account, MFA and private provisioning. No input values retained.');}
|
||||
}
|
||||
async function open(){
|
||||
let browser;
|
||||
try{const scope=runState(),identity=loadIdentity();browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_PATH||undefined});const context=await browser.newContext({viewport:{width:1440,height:1000},serviceWorkers:'block'});
|
||||
// Intercept every browser request, including form submissions and redirects.
|
||||
// Only the two pinned scripts already used by the application may load externally.
|
||||
// Production and other external requests, including form submissions, are blocked.
|
||||
let blockedExternal=0;
|
||||
await context.route('**/*',route=>{if(requestAllowed(route.request().url(),route.request().method(),route.request().resourceType()))return route.continue();blockedExternal++;return route.abort('blockedbyclient');});
|
||||
const page=await context.newPage();await login(page,identity);
|
||||
const visible=await page.locator('.project-card').evaluateAll(cards=>cards.map(card=>({id:Number(card.dataset.pdContextId),name:card.dataset.pdContextLabel})));
|
||||
check(workspaceAllowed(visible,scope.state.projects),'Unexpected project membership; operator review required');
|
||||
async function goto(route){const response=await page.goto(target(route));check(new URL(page.url()).origin===BASE,'Unexpected destination');return response;}
|
||||
async function post(route,fields){
|
||||
// Browser fetch is subject to the same origin gate, unlike context.request.
|
||||
const result=await page.evaluate(async ({url,fields})=>{const token=document.querySelector('input[name=__RequestVerificationToken]')?.value;if(!token)return {status:0};
|
||||
const response=await fetch(url,{method:'POST',credentials:'same-origin',body:new URLSearchParams({...fields,__RequestVerificationToken:token})});return {status:response.status};
|
||||
},{url:target(route),fields});check(result.status>=200&&result.status<400,'Normal application mutation failed');return result;
|
||||
}
|
||||
async function create(area,query,fields,prepare){
|
||||
let phase='form',invalidFields=[];try {
|
||||
if(area==='Projects')check(scope.state.projects.some(record=>record.id===null&&record.name===fields.ProjectName),'Register the run project before creating it');
|
||||
else check(scope.state.projects.length===1&&Number.isSafeInteger(scope.state.projects[0].id),'Create the registered disposable project first');
|
||||
check(['Projects','Books','Chapters','Characters','Locations','StoryAssets','PlotLines','PlotThreads'].includes(area),'Unsupported fixture record');
|
||||
check((await goto(`/${area}/Create${query||''}`)).status()===200,'Fixture create form unavailable');
|
||||
phase='fields';for(const [name,value]of Object.entries(fields)){const field=page.locator(`[name="${name}"]`).first();if(await field.evaluate(e=>e.tagName)==='SELECT')await field.selectOption(String(value));else await field.fill(String(value));}
|
||||
if(prepare)await prepare(page);
|
||||
phase='validation';invalidFields=await page.locator('main form.pd-record-form').evaluate(form=>Array.from(form.elements).filter(e=>e.willValidate&&!e.validity.valid).map(e=>e.name));check(invalidFields.length===0,'Fixture requires valid form fields');
|
||||
phase='submit';await Promise.all([page.waitForNavigation(),page.locator('main form.pd-record-form button[type=submit]').filter({hasText:/Save/}).evaluate(button=>button.form.requestSubmit(button))]);
|
||||
check(!/\/Save$/.test(new URL(page.url()).pathname),'Fixture form validation failed');
|
||||
phase='identity';let id=Number(new URL(page.url()).pathname.match(/\/(?:Details|Edit)\/(\d+)/)?.[1]);
|
||||
if(!id){const href=await page.locator(`main a[href*="/${area}/Edit/"],main a[href*="/${area}/Details/"]`).first().getAttribute('href');id=Number(href?.match(/\/(?:Edit|Details)\/(\d+)/)?.[1]);}
|
||||
check(Number.isSafeInteger(id)&&id>0,'Fixture record ID unavailable');return id;
|
||||
}catch(error){throw new Error('fixture-create:'+JSON.stringify({area,phase,path:new URL(page.url()).pathname,type:error.name,invalidFields}));}
|
||||
}
|
||||
async function project(){
|
||||
check(scope.state.projects.length===0,'One disposable project per run; reuse its books and records');
|
||||
const name='CYJ acceptance '+scope.id;
|
||||
// Persist intent before submitting, so interrupted creates can be recovered by exact name.
|
||||
const record={id:null,name};scope.state.projects.push(record);scope.save();
|
||||
record.id=await create('Projects','',{ProjectName:name,Description:'Disposable automated Development acceptance fixture.'});scope.save();return record.id;
|
||||
}
|
||||
async function cleanup(){
|
||||
for(const record of [...scope.state.projects]){
|
||||
check(record.name==='CYJ acceptance '+scope.id,'Cleanup scope mismatch');
|
||||
if(!record.id){await goto('/Projects');const matches=page.locator('a[href^="/Projects/Details/"]').filter({hasText:record.name});check(await matches.count()<=1,'Ambiguous recovery');if(await matches.count())record.id=Number((await matches.getAttribute('href')).split('/').pop());else{scope.state.projects.splice(scope.state.projects.indexOf(record),1);scope.save();continue;}scope.save();}
|
||||
let response=await goto('/Projects/Edit/'+record.id);
|
||||
if(response.status()===404){
|
||||
// A previous cleanup may have archived the project before it was interrupted.
|
||||
await goto('/Projects');
|
||||
}else{check(response.status()===200&&await page.locator('[name=ProjectName]').inputValue()===record.name,'Cleanup owner/name verification failed');await post('/Projects/Archive/'+record.id,{});await goto('/Projects');}
|
||||
// Server requires archived owner plus the exact confirmation name. Never delete accounts here.
|
||||
await post('/Projects/HardDeleteArchivedProject',{projectId:String(record.id),confirmationName:record.name});
|
||||
await goto('/Projects');check(await page.locator(`.project-card[data-pd-context-id="${record.id}"]`).count()===0,'Archived fixture still exists after cleanup');
|
||||
check((await goto('/Projects/Details/'+record.id)).status()===404,'Fixture cleanup not confirmed');
|
||||
scope.state.projects.splice(scope.state.projects.indexOf(record),1);scope.save();
|
||||
}
|
||||
}
|
||||
return {page,goto,post,create,project,cleanup,runId:scope.id,blockedExternal:()=>blockedExternal,async close(){await context.close();await browser.close();}};
|
||||
}catch{if(browser)await browser.close().catch(()=>{});throw new Error('Development acceptance session unavailable; check the launcher, fixture credentials/MFA and unexpected project membership. No input values logged.');}
|
||||
}
|
||||
module.exports={BASE,IDENTITY,target,requestAllowed,workspaceAllowed,loadIdentity,login,open};
|
||||
38
PlotLine.Tests/Browser/dev-acceptance.test.cjs
Normal file
38
PlotLine.Tests/Browser/dev-acceptance.test.cjs
Normal file
@ -0,0 +1,38 @@
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {target,requestAllowed,workspaceAllowed,loadIdentity,login}=require('./dev-acceptance.cjs');
|
||||
test('only the fixed HTTPS Development origin is accepted',()=>{
|
||||
assert.equal(target('/Projects'),'https://dev.plotdirector.com/Projects');
|
||||
for(const url of ['https://app.plotdirector.com','//app.plotdirector.com','/\\app.plotdirector.com','http://dev.plotdirector.com'])assert.throws(()=>target(url));
|
||||
for(const url of ['https://app.plotdirector.com','https://plotdirector.com','http://dev.plotdirector.com','file:///etc/passwd','bad'])assert.equal(requestAllowed(url),false);
|
||||
assert.equal(requestAllowed('https://dev.plotdirector.com/Projects/Save'),true);
|
||||
const cdn='https://cdn.jsdelivr.net/npm/chart.js@4.4.9/dist/chart.umd.min.js';
|
||||
assert.equal(requestAllowed(cdn,'GET','script'),true);
|
||||
assert.equal(requestAllowed(cdn,'POST','script'),false);
|
||||
assert.equal(requestAllowed(cdn,'GET','fetch'),false);
|
||||
assert.equal(requestAllowed(cdn+'?input=synthetic','GET','script'),false);
|
||||
});
|
||||
test('identity requires private owner-only storage and dedicated Development scope',()=>{
|
||||
const root=fs.mkdtempSync(path.join(os.tmpdir(),'pd-browser-security-'));fs.chmodSync(root,0o700);
|
||||
const file=path.join(root,'identity.json');
|
||||
const identity={UserID:1,Email:'pwa-browser-'+'a'.repeat(32)+'@example.invalid',Password:'x'.repeat(48),Database:'PlotDirector_Development',Origin:'https://dev.plotdirector.com',Worker:'application',Purpose:'CYJ Development browser acceptance'};
|
||||
try{fs.writeFileSync(file,JSON.stringify(identity),{mode:0o600});assert.equal(loadIdentity(file).UserID,1);
|
||||
fs.chmodSync(file,0o644);assert.throws(()=>loadIdentity(file));fs.chmodSync(file,0o600);
|
||||
fs.linkSync(file,path.join(root,'link'));assert.throws(()=>loadIdentity(file));fs.unlinkSync(path.join(root,'link'));
|
||||
for(const change of [{Database:'PlotLine'},{Origin:'https://app.plotdirector.com'},{Worker:'website'},{Email:'owner@example.invalid'}]){fs.writeFileSync(file,JSON.stringify({...identity,...change}));assert.throws(()=>loadIdentity(file));}
|
||||
const secret='synthetic-sensitive-invalid-json';fs.writeFileSync(file,'{"Password":"'+secret+'"');assert.throws(()=>loadIdentity(file),error=>!error.message.includes(secret));
|
||||
fs.unlinkSync(file);fs.symlinkSync('/etc/passwd',file);assert.throws(()=>loadIdentity(file));
|
||||
}finally{fs.rmSync(root,{recursive:true,force:true});}
|
||||
});
|
||||
test('login failure never returns Playwright input values or passwords',async()=>{
|
||||
const secret='synthetic-sensitive-test-value';
|
||||
const page={goto:async()=>({status:()=>200}),locator:()=>({fill:async()=>{throw new Error('fill call log: '+secret);}})};
|
||||
await assert.rejects(login(page,{Email:'fixture@example.invalid',Password:secret}),error=>!error.message.includes(secret)&&error.cause===undefined);
|
||||
});
|
||||
|
||||
test('unexpected project memberships fail closed while registered interrupted creates remain recoverable',()=>{
|
||||
assert.equal(workspaceAllowed([],[]),true);
|
||||
assert.equal(workspaceAllowed([{id:1,name:'fixture'}],[{id:1,name:'fixture'}]),true);
|
||||
assert.equal(workspaceAllowed([{id:1,name:'fixture'}],[{id:null,name:'fixture'}]),true);
|
||||
assert.equal(workspaceAllowed([{id:2,name:'unrelated'}],[{id:1,name:'fixture'}]),false);
|
||||
assert.equal(workspaceAllowed([{id:1,name:'renamed'}],[{id:1,name:'fixture'}]),false);
|
||||
});
|
||||
@ -13,11 +13,54 @@ using PlotLine.Services;
|
||||
internal static class DevBrowserIdentity
|
||||
{
|
||||
private sealed record Identity(int UserID, string Email, string Password, string Database);
|
||||
private static async Task VerifiedBackupAsync()
|
||||
{
|
||||
// A uniquely named copy-only backup precedes all provisioning writes.
|
||||
var backup = $"/var/opt/mssql/backup/pwa-desktop-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak";
|
||||
// Operator-only setup reuses the installed Development backup worker. Runtime
|
||||
// SQL permissions deliberately do not include BACKUP DATABASE; never grant it.
|
||||
const string backupCode = """
|
||||
import sys, os, grp, fcntl, tempfile, uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, '/usr/local/lib/plotdirector-dev-deployment')
|
||||
from development import Development, DevelopmentWorker
|
||||
from release import load, require, safe_name, verify_bundle
|
||||
cfg = Development().configuration()
|
||||
backup = sys.argv[1]
|
||||
require(backup.startswith(cfg['database_backup_directory']+'/pwa-desktop-') and backup.endswith('.bak') and '..' not in backup, 'Invalid fixture backup')
|
||||
with open(Path(cfg['root'])/'deployment.lock', 'r+') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
active = load(Path(cfg['root'])/'active-deployment.json')
|
||||
source = Path(cfg['inbox'])/safe_name(active['release'])
|
||||
group = grp.getgrnam(cfg['migration_account']).gr_gid
|
||||
with tempfile.TemporaryDirectory(prefix='.browser-backup-', dir=cfg['root']) as temporary:
|
||||
os.chown(temporary, 0, group); os.chmod(temporary, 0o750)
|
||||
manifest, authorization, payload = verify_bundle(source, temporary, cfg['public_key'])
|
||||
require(authorization['package_sha256'] == active['package_sha256'], 'Active package mismatch')
|
||||
for entry in [payload, *payload.rglob('*')]:
|
||||
os.chown(entry, 0, group); entry.chmod(0o750 if entry.is_dir() else 0o640)
|
||||
worker = DevelopmentWorker(cfg)
|
||||
try:
|
||||
worker.call('begin', package_root=str(payload), deployment_id='browser-backup-'+uuid.uuid4().hex, package_sha256=authorization['package_sha256'])
|
||||
require(worker.call('backup', path=backup)['verified'], 'Backup not verified')
|
||||
finally:
|
||||
worker.close()
|
||||
""";
|
||||
var backupStart = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var part in new[] { "-n", "/usr/bin/python3", "-I", "-c", backupCode, backup }) backupStart.ArgumentList.Add(part);
|
||||
using var backupProcess = Process.Start(backupStart)!;
|
||||
var backupOutput = backupProcess.StandardOutput.ReadToEndAsync();
|
||||
var backupErrors = backupProcess.StandardError.ReadToEndAsync();
|
||||
await backupProcess.WaitForExitAsync();
|
||||
await Task.WhenAll(backupOutput, backupErrors); // Never log protected operational output.
|
||||
if (backupProcess.ExitCode != 0) throw new InvalidOperationException("Existing Development backup worker refused provisioning; no identity created");
|
||||
}
|
||||
|
||||
public static async Task RunAsync(string[] args)
|
||||
{
|
||||
if (!OperatingSystem.IsLinux()) throw new PlatformNotSupportedException("Development provisioning runs only on the Linux development host");
|
||||
if (args.Length != 3 || args[1] is not ("create" or "cleanup") || !Path.GetFullPath(args[2]).StartsWith("/tmp/pd-dev-browser-", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("Use --dev-browser-identity create|cleanup /tmp/pd-dev-browser-<unique>.json");
|
||||
if (!OperatingSystem.IsLinux() || !string.Equals(Dns.GetHostName(), "atlas", StringComparison.OrdinalIgnoreCase)) throw new PlatformNotSupportedException("Development provisioning runs only on the Linux development host");
|
||||
if (args.Length != 3 || args[1] is not ("create" or "cleanup" or "configure-worker") || (args[1] == "configure-worker" ? Path.GetFullPath(args[2]) != Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config/cyj/credentials/application-browser.json") : !Path.GetFullPath(args[2]).StartsWith("/tmp/pd-dev-browser-", StringComparison.Ordinal)))
|
||||
throw new InvalidOperationException("Use --dev-browser-identity create|cleanup /tmp/pd-dev-browser-<unique>.json, or configure-worker with the private application-browser.json");
|
||||
var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var part in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(part);
|
||||
using var process = Process.Start(start)!;
|
||||
@ -25,7 +68,8 @@ internal static class DevBrowserIdentity
|
||||
await process.WaitForExitAsync();
|
||||
if (process.ExitCode != 0) throw new InvalidOperationException("Development configuration unavailable");
|
||||
var connectionString = environment.Split('\n').Single(line => line.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\'');
|
||||
if (new SqlConnectionStringBuilder(connectionString).InitialCatalog != "PlotDirector_Development") throw new InvalidOperationException("Only the development database is permitted");
|
||||
var target = new SqlConnectionStringBuilder(connectionString);
|
||||
if (target.InitialCatalog != "PlotDirector_Development" || target.DataSource is not ("192.168.10.10,1433" or "tcp:192.168.10.10,1433")) throw new InvalidOperationException("Only the development database is permitted");
|
||||
using var connection = new SqlConnection(connectionString);
|
||||
await connection.OpenAsync();
|
||||
using var verify = connection.CreateCommand(); verify.CommandText = "SELECT DB_NAME()";
|
||||
@ -37,17 +81,7 @@ internal static class DevBrowserIdentity
|
||||
if (args[1] == "create")
|
||||
{
|
||||
if (File.Exists(path)) throw new InvalidOperationException("Refusing to overwrite an identity file");
|
||||
// A uniquely named copy-only backup precedes all provisioning writes.
|
||||
var backup = $"/var/opt/mssql/backup/pwa-desktop-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak";
|
||||
using var command = connection.CreateCommand(); command.CommandTimeout = 300;
|
||||
command.CommandText = "BACKUP DATABASE [PlotDirector_Development] TO DISK = @path WITH COPY_ONLY, CHECKSUM;";
|
||||
command.Parameters.AddWithValue("@path", backup);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
var checkBackup = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var part in new[] { "-n", "docker", "exec", "atlas-sql-server", "test", "-s", backup }) checkBackup.ArgumentList.Add(part);
|
||||
using var backupCheck = Process.Start(checkBackup)!;
|
||||
await backupCheck.WaitForExitAsync();
|
||||
if (backupCheck.ExitCode != 0) throw new InvalidOperationException("Development backup file verification failed");
|
||||
await VerifiedBackupAsync();
|
||||
var email = $"pwa-browser-{Guid.NewGuid():N}@example.invalid";
|
||||
var password = Convert.ToBase64String(RandomNumberGenerator.GetBytes(36)) + "aA1!";
|
||||
var user = await users.CreateAsync(email, "Desktop Verification Author", new PasswordService().HashPassword(password), emailConfirmed: false);
|
||||
@ -60,6 +94,46 @@ internal static class DevBrowserIdentity
|
||||
await JsonSerializer.SerializeAsync(stream, new Identity(user.UserID, email, password, "PlotDirector_Development"));
|
||||
Console.WriteLine("Dedicated development browser identity provisioned through normal account repositories; credentials stored privately. No production access.");
|
||||
}
|
||||
else if (args[1] == "configure-worker")
|
||||
{
|
||||
var identity = JsonSerializer.Deserialize<Identity>(await File.ReadAllTextAsync(path))!;
|
||||
var user = await users.GetByEmailAsync(identity.Email);
|
||||
if (identity.Database != "PlotDirector_Development" || !Regex.IsMatch(identity.Email, @"^pwa-browser-[a-f0-9]{32}@example\.invalid$") || user is null || user.UserID != identity.UserID || !new PasswordService().VerifyPassword(identity.Password, user.PasswordHash))
|
||||
throw new InvalidOperationException("Dedicated worker identity scope mismatch");
|
||||
var read = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var part in new[] { "-n", "cat", "/opt/plotdirector-dev/current/appsettings.json" }) read.ArgumentList.Add(part);
|
||||
using var settingsProcess = Process.Start(read)!;
|
||||
var settings = await settingsProcess.StandardOutput.ReadToEndAsync();
|
||||
await settingsProcess.WaitForExitAsync();
|
||||
if (settingsProcess.ExitCode != 0) throw new InvalidOperationException("Development administrator policy unavailable");
|
||||
using var settingsStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(settings));
|
||||
var overrides = environment.Split('\n').Where(line => line.StartsWith("Admin__AllowedEmails__", StringComparison.Ordinal))
|
||||
.Select(line => line.Split('=', 2)).ToDictionary(parts => parts[0].Replace("__", ":"), parts => (string?)parts[1].Trim().Trim('"', '\''));
|
||||
var administratorConfig = new ConfigurationBuilder().AddJsonStream(settingsStream).AddInMemoryCollection(overrides).Build();
|
||||
var administrators = administratorConfig.GetSection("Admin:AllowedEmails").Get<string[]>() ?? [];
|
||||
if (administrators.Length != 1 || administrators.Any(email => email.Equals(identity.Email, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException("A single configured human administrator is required for the provisioning audit; never grant the fixture administrator access");
|
||||
var administrator = await users.GetByEmailAsync(administrators[0]);
|
||||
if (administrator is null || !administrator.EmailConfirmed || administrator.UserID == identity.UserID)
|
||||
throw new InvalidOperationException("Configured provisioning sponsor is unavailable");
|
||||
var subscriptions = new SubscriptionRepository(factory);
|
||||
var current = await subscriptions.GetCurrentSubscriptionAsync(identity.UserID)
|
||||
?? throw new InvalidOperationException("Dedicated account has no normal writer subscription");
|
||||
var existingOverride = await subscriptions.GetActiveOverrideAsync(identity.UserID, DateTime.UtcNow);
|
||||
if (existingOverride is not null && existingOverride.ExpiryDateUTC is null && existingOverride.SubscriptionLevelID == current.SubscriptionLevelID)
|
||||
{
|
||||
Console.WriteLine("Dedicated Development writer entitlement already configured; no changes made.");
|
||||
return;
|
||||
}
|
||||
await VerifiedBackupAsync();
|
||||
await subscriptions.SaveOverrideAsync(identity.UserID, current.SubscriptionLevelID, DateTime.UtcNow, null,
|
||||
"Owner-authorised permanent Development-only CYJ browser acceptance fixture; same ordinary writer plan, no billing-provider change.", administrator.UserID);
|
||||
var active = await subscriptions.GetActiveOverrideAsync(identity.UserID, DateTime.UtcNow);
|
||||
var future = await subscriptions.GetActiveOverrideAsync(identity.UserID, DateTime.UtcNow.AddYears(1));
|
||||
if (active is null || active.ExpiryDateUTC is not null || active.SubscriptionLevelID != current.SubscriptionLevelID || future?.SubscriptionLevelID != current.SubscriptionLevelID)
|
||||
throw new InvalidOperationException("Dedicated writer entitlement verification failed");
|
||||
Console.WriteLine("Non-expiring Development writer entitlement provisioned using the existing audited administrative override; no administrator role or billing change.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var identity = JsonSerializer.Deserialize<Identity>(await File.ReadAllTextAsync(path))!;
|
||||
|
||||
@ -106,7 +106,17 @@ if (args.Contains("--writing-solver-curated-v2"))
|
||||
|
||||
if (args.Contains("--dev-browser-identity"))
|
||||
{
|
||||
await DevBrowserIdentity.RunAsync(args);
|
||||
try
|
||||
{
|
||||
await DevBrowserIdentity.RunAsync(args);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
// Operational setup handles protected configuration in memory. Do not emit
|
||||
// raw exception details or create an unhandled-exception core dump.
|
||||
Console.Error.WriteLine($"Development browser identity operation refused ({error.GetType().Name}); inspect safe provisioning state. No credentials logged.");
|
||||
Environment.ExitCode = 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
39
Tools/BrowserAcceptance/install_identity.py
Normal file
39
Tools/BrowserAcceptance/install_identity.py
Normal file
@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Securely install an identity produced by the approved DevBrowserIdentity helper.
|
||||
This stores credentials only; it does not create users, bypass MFA or access SQL.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
|
||||
|
||||
def install(source):
|
||||
if not str(source).startswith('/tmp/pd-dev-browser-'):
|
||||
raise ValueError('Use an approved newly provisioned fixture identity')
|
||||
fd=os.open(source,os.O_RDONLY|os.O_NOFOLLOW)
|
||||
with os.fdopen(fd) as stream:
|
||||
st=os.fstat(stream.fileno())
|
||||
if st.st_uid!=os.getuid() or not stat.S_ISREG(st.st_mode) or stat.S_IMODE(st.st_mode)!=0o600 or st.st_nlink!=1 or st.st_size>16384:
|
||||
raise ValueError('Private provisioning file required')
|
||||
identity=json.load(stream)
|
||||
if identity['Database']!='PlotDirector_Development' or not re.fullmatch(r'pwa-browser-[a-f0-9]{32}@example.invalid',identity['Email']) or not isinstance(identity['UserID'],int) or identity['UserID']<1 or len(identity['Password'])<40:
|
||||
raise ValueError('Dedicated Development provisioning identity required')
|
||||
identity.update(Origin='https://dev.plotdirector.com',Worker='application',Purpose='CYJ Development browser acceptance')
|
||||
directory=Path.home()/'.config/cyj/credentials'
|
||||
directory.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if directory.is_symlink() or directory.stat().st_uid!=os.getuid() or stat.S_IMODE(directory.stat().st_mode)!=0o700:
|
||||
raise ValueError('Private credential directory required')
|
||||
target=directory/'application-browser.json'
|
||||
fd=os.open(target,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
|
||||
with os.fdopen(fd,'w') as stream:
|
||||
json.dump(identity,stream);stream.flush();os.fsync(stream.fileno())
|
||||
source.unlink()
|
||||
print('Dedicated Development browser identity installed privately; provisioning file removed. No credential values printed.')
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('source',type=Path);args=parser.parse_args()
|
||||
try:install(args.source)
|
||||
except (ValueError,OSError,KeyError,TypeError):raise SystemExit('Identity installation refused; inspect private provisioning and existing identity without printing credentials.')
|
||||
65
Tools/BrowserAcceptance/run.py
Normal file
65
Tools/BrowserAcceptance/run.py
Normal file
@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run ordinary Node/Playwright acceptance under an OS-held dedicated-account lock.
|
||||
No sudo, SQL access, secrets in arguments, or authentication bypasses.
|
||||
"""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
|
||||
def run(script, arguments, resume=None):
|
||||
if os.environ.get('CYJ_CONTROLLER_WORKER', 'application') != 'application':
|
||||
raise ValueError('Application browser identity is restricted to the application worker')
|
||||
root = Path.home()/'.local/state/cyj/browser/application'
|
||||
root.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
if root.is_symlink() or root.stat().st_uid != os.getuid():
|
||||
raise ValueError('Invalid private browser state directory')
|
||||
root.chmod(0o700)
|
||||
fd = os.open(root/'session.lock', os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
st = os.fstat(fd)
|
||||
if not stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid() or stat.S_IMODE(st.st_mode) != 0o600 or st.st_nlink != 1:
|
||||
raise ValueError('Invalid browser lock')
|
||||
try: fcntl.flock(fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
except BlockingIOError: raise ValueError('Dedicated browser identity is busy; retry after the current session exits')
|
||||
if resume and (len(resume)!=32 or any(c not in '0123456789abcdef' for c in resume)):
|
||||
raise ValueError('Resume requires an existing full run ID')
|
||||
run_id = resume or uuid.uuid4().hex
|
||||
state = root/(run_id+'.json')
|
||||
if resume and not state.is_file(): raise ValueError('Unknown acceptance run')
|
||||
if not resume:
|
||||
# Pending fixtures must be explicitly reconciled, never silently replaced.
|
||||
for candidate in root.glob('*.json'):
|
||||
if json.loads(candidate.read_text()).get('projects'):
|
||||
raise ValueError('Unclean acceptance run exists; resume its cleanup before starting another session')
|
||||
os.ftruncate(fd,0);os.write(fd,run_id.encode());os.lseek(fd,0,0)
|
||||
env = {**os.environ, 'PD_DEV_BROWSER_RUN_ID':run_id, 'PD_DEV_BROWSER_STATE':str(state),
|
||||
'PD_DEV_BROWSER_LOCK_FD':str(fd)}
|
||||
# Playwright protocol/API debug output can include password fill values.
|
||||
for key in ('DEBUG', 'PWDEBUG', 'PLAYWRIGHT_TRACE_DIR', 'CHROME_LOG_FILE'):
|
||||
env.pop(key, None)
|
||||
result = subprocess.run(['/usr/bin/node',str(Path(script).resolve()),*arguments],env=env,pass_fds=(fd,))
|
||||
return result.returncode
|
||||
finally:os.close(fd)
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--resume')
|
||||
parser.add_argument('script',type=Path)
|
||||
parser.add_argument('arguments',nargs=argparse.REMAINDER)
|
||||
args=parser.parse_args()
|
||||
if not args.script.is_file():raise ValueError('Acceptance script unavailable')
|
||||
return run(args.script,args.arguments,args.resume)
|
||||
|
||||
if __name__=='__main__':
|
||||
try:raise SystemExit(main())
|
||||
except (ValueError,OSError):
|
||||
print('Browser acceptance launcher refused: check the dedicated-account lock, pending run cleanup and private state permissions. No credentials logged.',file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
39
Tools/BrowserAcceptance/test_run.py
Normal file
39
Tools/BrowserAcceptance/test_run.py
Normal file
@ -0,0 +1,39 @@
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec=importlib.util.spec_from_file_location('acceptance_run',Path(__file__).with_name('run.py'))
|
||||
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
||||
|
||||
class LauncherTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp=tempfile.TemporaryDirectory();self.home=Path(self.temp.name)
|
||||
self.patch=patch.object(Path,'home',return_value=self.home);self.patch.start()
|
||||
self.root=self.home/'.local/state/cyj/browser/application';self.root.mkdir(parents=True,mode=0o700)
|
||||
def tearDown(self):self.patch.stop();self.temp.cleanup()
|
||||
def test_concurrent_session_is_rejected_without_launch(self):
|
||||
with (self.root/'session.lock').open('w') as lock:
|
||||
(self.root/'session.lock').chmod(0o600);fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
with patch.object(module.subprocess,'run') as launch:
|
||||
with self.assertRaises(ValueError):module.run('/fixture.cjs',[])
|
||||
launch.assert_not_called()
|
||||
def test_pending_fixtures_require_explicit_resume_and_valid_run(self):
|
||||
run='a'*32;(self.root/(run+'.json')).write_text(json.dumps({'runId':run,'projects':[{'id':1}]}))
|
||||
with patch.object(module.subprocess,'run',return_value=subprocess.CompletedProcess([],0)) as launch:
|
||||
with self.assertRaises(ValueError):module.run('/fixture.cjs',[])
|
||||
with self.assertRaises(ValueError):module.run('/fixture.cjs',[],'../escape')
|
||||
with patch.dict(module.os.environ,{'DEBUG':'pw:api','PWDEBUG':'1'}):
|
||||
self.assertEqual(module.run('/fixture.cjs',[],run),0)
|
||||
kwargs=launch.call_args.kwargs
|
||||
self.assertEqual(kwargs['env']['PD_DEV_BROWSER_RUN_ID'],run)
|
||||
self.assertIn(int(kwargs['env']['PD_DEV_BROWSER_LOCK_FD']),kwargs['pass_fds'])
|
||||
self.assertNotIn('Password',kwargs['env'])
|
||||
self.assertNotIn('DEBUG',kwargs['env'])
|
||||
self.assertNotIn('PWDEBUG',kwargs['env'])
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Loading…
x
Reference in New Issue
Block a user