@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +203 -0
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +93 -2
- package/dist/index.js +125 -0
- package/package.json +57 -4
- package/template/Dockerfile +37 -0
- package/template/README.md +389 -0
- package/template/_dockerignore +6 -0
- package/template/_env.example +122 -0
- package/template/_github/workflows/ci.yml +23 -0
- package/template/_gitignore +8 -0
- package/template/_prettierrc +6 -0
- package/template/apps/api/API.md +119 -0
- package/template/apps/api/package.json +39 -0
- package/template/apps/api/src/auth.ts +55 -0
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +204 -0
- package/template/apps/api/src/cli.ts +99 -0
- package/template/apps/api/src/config.ts +180 -0
- package/template/apps/api/src/custody.ts +358 -0
- package/template/apps/api/src/dev-index.ts +120 -0
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/env.ts +14 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +57 -0
- package/template/apps/api/src/index-client.ts +261 -0
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +58 -0
- package/template/apps/api/src/parties.ts +68 -0
- package/template/apps/api/src/platform.ts +176 -0
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +125 -0
- package/template/apps/api/src/reader.ts +265 -0
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +613 -0
- package/template/apps/api/src/store.ts +426 -0
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +359 -0
- package/template/apps/api/src/worker.ts +113 -0
- package/template/apps/api/src/writer.ts +603 -0
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +160 -0
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +32 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +147 -0
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/tsconfig.json +9 -0
- package/template/apps/api/vitest.config.ts +12 -0
- package/template/apps/web/components.json +21 -0
- package/template/apps/web/index.html +12 -0
- package/template/apps/web/package.json +33 -0
- package/template/apps/web/src/app.tsx +55 -0
- package/template/apps/web/src/components/bits.tsx +188 -0
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +135 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +244 -0
- package/template/apps/web/src/components/read-passport.tsx +49 -0
- package/template/apps/web/src/components/reading.tsx +150 -0
- package/template/apps/web/src/components/ui/alert.tsx +65 -0
- package/template/apps/web/src/components/ui/badge.tsx +47 -0
- package/template/apps/web/src/components/ui/button.tsx +63 -0
- package/template/apps/web/src/components/ui/card.tsx +91 -0
- package/template/apps/web/src/components/ui/dialog.tsx +156 -0
- package/template/apps/web/src/components/ui/input.tsx +20 -0
- package/template/apps/web/src/components/ui/label.tsx +21 -0
- package/template/apps/web/src/components/ui/select.tsx +189 -0
- package/template/apps/web/src/components/ui/separator.tsx +25 -0
- package/template/apps/web/src/components/ui/table.tsx +115 -0
- package/template/apps/web/src/components/ui/tabs.tsx +90 -0
- package/template/apps/web/src/components/ui/textarea.tsx +17 -0
- package/template/apps/web/src/index.css +81 -0
- package/template/apps/web/src/lib/api.ts +396 -0
- package/template/apps/web/src/lib/auth.ts +10 -0
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +87 -0
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/lib/session.tsx +92 -0
- package/template/apps/web/src/lib/use-load.ts +46 -0
- package/template/apps/web/src/main.tsx +18 -0
- package/template/apps/web/src/pages/accept.tsx +113 -0
- package/template/apps/web/src/pages/brand.tsx +94 -0
- package/template/apps/web/src/pages/brands.tsx +104 -0
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/home.tsx +51 -0
- package/template/apps/web/src/pages/new-passport.tsx +137 -0
- package/template/apps/web/src/pages/operations.tsx +169 -0
- package/template/apps/web/src/pages/passport.tsx +632 -0
- package/template/apps/web/src/pages/public-passport.tsx +64 -0
- package/template/apps/web/src/pages/sign-in.tsx +93 -0
- package/template/apps/web/src/pages/verify.tsx +30 -0
- package/template/apps/web/src/pages/wallet.tsx +141 -0
- package/template/apps/web/tsconfig.json +29 -0
- package/template/apps/web/vite.config.ts +23 -0
- package/template/deploy/compose.yml +38 -0
- package/template/package.json +48 -0
- package/template/tsconfig.base.json +13 -0
|
@@ -0,0 +1,1038 @@
|
|
|
1
|
+
// The exit exercise: leave one deployment and carry on in another.
|
|
2
|
+
//
|
|
3
|
+
// Deployment A is this application as it runs by default: MongoDB for its
|
|
4
|
+
// records and for the EPCIS exchange, and the two sector profiles read from
|
|
5
|
+
// the folder the profiles package ships. It issues a battery and a textile
|
|
6
|
+
// passport, imports and pulls EPCIS events, and is exported with the
|
|
7
|
+
// operator's `export` command. Then A is switched off: its database and its
|
|
8
|
+
// index are stopped, and nothing can be read from it again.
|
|
9
|
+
//
|
|
10
|
+
// Deployment B is configured differently on the two boundaries a replacement
|
|
11
|
+
// must be shown at. Its EPCIS store is the file-system adapter over a folder,
|
|
12
|
+
// not MongoDB, and its profiles are read from a profile bundle the restore
|
|
13
|
+
// installs, not from the package's folder. It has a database, an index and
|
|
14
|
+
// folders of its own. The operator's `restore` command is given the package
|
|
15
|
+
// and the key it must be signed under. From then on the network is kept to
|
|
16
|
+
// B's own services and the one EPCIS source: any other attempt is refused and
|
|
17
|
+
// recorded, and the record must be empty. The guard holds this process only:
|
|
18
|
+
// the second restore of B, run as `npm run restore` in a process of its own,
|
|
19
|
+
// is outside it.
|
|
20
|
+
//
|
|
21
|
+
// Deployment C is restored from the same package with keys of its own, none
|
|
22
|
+
// of them A's. It shows what the keys are for: C reads every passport and
|
|
23
|
+
// verifies it as A did, except for the issuer's authority, which it does not
|
|
24
|
+
// confirm without A's brand secret, and C is refused every write by name.
|
|
25
|
+
//
|
|
26
|
+
// What is real here and what stands in:
|
|
27
|
+
//
|
|
28
|
+
// - MongoDB is a real server, started for the test: one for A and one for
|
|
29
|
+
// B. C keeps its own database on B's server.
|
|
30
|
+
// - Each index is the reference index's own code over in-memory storage,
|
|
31
|
+
// with its header checks off. It admits and serves and proves no
|
|
32
|
+
// inclusion: no reading here says a state is in a block.
|
|
33
|
+
// - The wallet is the test wallet, with fixed keys and made-up funding.
|
|
34
|
+
// B holding the same keys stands in for the wallet's own recovery, which
|
|
35
|
+
// is what carries keys between deployments. The package carries none.
|
|
36
|
+
// - The EPCIS source is the small fixture server of these tests.
|
|
37
|
+
// - Sign-in is the development session in all three deployments. Accounts
|
|
38
|
+
// and memberships are not carried by an export.
|
|
39
|
+
import { spawn } from 'node:child_process'
|
|
40
|
+
import { createHash } from 'node:crypto'
|
|
41
|
+
import { once } from 'node:events'
|
|
42
|
+
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
43
|
+
import type { Server } from 'node:http'
|
|
44
|
+
import type { AddressInfo } from 'node:net'
|
|
45
|
+
import { tmpdir } from 'node:os'
|
|
46
|
+
import { dirname, join } from 'node:path'
|
|
47
|
+
import { MongoClient } from 'mongodb'
|
|
48
|
+
import { MongoMemoryServer } from 'mongodb-memory-server'
|
|
49
|
+
import { PrivateKey } from '@bsv/sdk'
|
|
50
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
|
51
|
+
import { canonicalJson, evidencePackageSigningKey, signEvidenceManifest, type EvidencePackageManifest } from '@bsv/dpp-protocol'
|
|
52
|
+
import { CURRENT_SECTOR_BINDINGS, profileBindingDigest } from '@bsv/dpp-profiles'
|
|
53
|
+
import { EPCIS_GS1_ARTEFACTS } from '@bsv/dpp-credentials'
|
|
54
|
+
import { EPCIS_RECORD_KINDS, checkEpcisExchangeInvariants, type EpcisExchangeStorage } from '@bsv/dpp-credentials/epcis-exchange'
|
|
55
|
+
import { loadConfig } from '../src/config.js'
|
|
56
|
+
import { startDevIndex, type DevIndex } from '../src/dev-index.js'
|
|
57
|
+
import { startEpcisExchange, type EpcisExchange } from '../src/epcis/exchange.js'
|
|
58
|
+
import { mintGtin } from '../src/identifiers.js'
|
|
59
|
+
import { openPlatform, type Platform } from '../src/platform.js'
|
|
60
|
+
import { runExportCommand, runRemapCommand, runRestoreCommand } from '../src/portability/commands.js'
|
|
61
|
+
import type { ApplicationExportDescriptor } from '../src/portability/package.js'
|
|
62
|
+
import type { RestoreReport } from '../src/portability/restore.js'
|
|
63
|
+
import type { AuthorisedReading, PassportReading } from '../src/reader.js'
|
|
64
|
+
import { createServer } from '../src/server.js'
|
|
65
|
+
import { developer, epcisDocument, eventId, gs1Dir, item, objectEvent, sha256, startEpcisSource, utf8, type FixtureSource, type Json } from './epcis-fixtures.js'
|
|
66
|
+
import { guardNetwork, type NetworkGuard } from './network-guard.js'
|
|
67
|
+
|
|
68
|
+
/* --------------------------------- secrets ------------------------------- */
|
|
69
|
+
|
|
70
|
+
// Each is in no fixture and no key. Wherever one turns up, it was copied there.
|
|
71
|
+
const SOURCE_SECRET = 'EXIT-SOURCE-CREDENTIAL-6E2A91D4C7'
|
|
72
|
+
const BRAND_SECRET = 'e1'.repeat(32)
|
|
73
|
+
const IDENTITY_SECRET = 'e2'.repeat(32)
|
|
74
|
+
const AUTH_SECRET = 'e3'.repeat(32)
|
|
75
|
+
const RESTRICTED = 'EXIT-RESTRICTED-CANARY-93B7F1'
|
|
76
|
+
/** The test wallet's root key, which both deployments hold: the stand-in for the wallet's own recovery. */
|
|
77
|
+
const WALLET_ROOT = '11'.repeat(32)
|
|
78
|
+
const PUBLISHER_KEY = PrivateKey.fromHex(WALLET_ROOT).toPublicKey().toString()
|
|
79
|
+
|
|
80
|
+
const scratch = mkdtempSync(join(tmpdir(), 'dpp-exit-exercise-'))
|
|
81
|
+
const AUTHORISED = join(scratch, 'export-authorised')
|
|
82
|
+
const PUBLIC = join(scratch, 'export-public')
|
|
83
|
+
const MANAGED_RECOVERY = join(scratch, 'export-managed-recovery')
|
|
84
|
+
|
|
85
|
+
/* ------------------------------- deployments ----------------------------- */
|
|
86
|
+
|
|
87
|
+
interface Answer {
|
|
88
|
+
status: number
|
|
89
|
+
bytes: Uint8Array
|
|
90
|
+
text: string
|
|
91
|
+
body: any
|
|
92
|
+
headers: Headers
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
interface Deployment {
|
|
96
|
+
platform: Platform
|
|
97
|
+
exchange: EpcisExchange
|
|
98
|
+
lines: string[]
|
|
99
|
+
base: string
|
|
100
|
+
get(path: string): Promise<Answer>
|
|
101
|
+
post(path: string, body: unknown): Promise<Answer>
|
|
102
|
+
upload(path: string, bytes: Uint8Array): Promise<Answer>
|
|
103
|
+
close(): Promise<void>
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The API as main.ts assembles it, from an environment: the platform in its live mode, the exchange beside it and the server. */
|
|
107
|
+
async function start(env: Record<string, string>, onListen?: (port: number) => void): Promise<Deployment> {
|
|
108
|
+
const config = loadConfig(env)
|
|
109
|
+
const lines: string[] = []
|
|
110
|
+
const log = (line: string): void => void lines.push(line)
|
|
111
|
+
const platform = await openPlatform({ config, mode: 'live', log })
|
|
112
|
+
const exchange = await startEpcisExchange({ config: config.epcis, ...(platform.db == null ? {} : { db: platform.db }), log })
|
|
113
|
+
const server: Server = createServer({ platform, exchange, devSession: developer }).listen(0, '127.0.0.1')
|
|
114
|
+
await once(server, 'listening')
|
|
115
|
+
const port = (server.address() as AddressInfo).port
|
|
116
|
+
onListen?.(port)
|
|
117
|
+
const base = `http://127.0.0.1:${port}`
|
|
118
|
+
const answer = async (response: Response): Promise<Answer> => {
|
|
119
|
+
const bytes = new Uint8Array(await response.arrayBuffer())
|
|
120
|
+
const text = new TextDecoder().decode(bytes)
|
|
121
|
+
let body: unknown
|
|
122
|
+
try {
|
|
123
|
+
body = text === '' ? undefined : JSON.parse(text)
|
|
124
|
+
} catch {
|
|
125
|
+
body = undefined
|
|
126
|
+
}
|
|
127
|
+
return { status: response.status, bytes, text, body, headers: response.headers }
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
platform,
|
|
131
|
+
exchange,
|
|
132
|
+
lines,
|
|
133
|
+
base,
|
|
134
|
+
get: async (path) => answer(await fetch(`${base}${path}`)),
|
|
135
|
+
post: async (path, body) => answer(await fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })),
|
|
136
|
+
upload: async (path, bytes) => answer(await fetch(`${base}${path}`, { method: 'POST', headers: { 'content-type': 'application/ld+json' }, body: bytes as unknown as BodyInit })),
|
|
137
|
+
close: async () => {
|
|
138
|
+
server.closeAllConnections()
|
|
139
|
+
await new Promise<void>((resolve) => server.close(() => resolve()))
|
|
140
|
+
await exchange.close()
|
|
141
|
+
await platform.close()
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const ref = (value: string): string => encodeURIComponent(value)
|
|
147
|
+
const portOf = (address: string): string => new URL(address).port
|
|
148
|
+
|
|
149
|
+
/** A command's function, called in this process: its exit code and every line it printed. */
|
|
150
|
+
async function command(run: (args: string[], context: { env: NodeJS.ProcessEnv; out: (line: string) => void; cwd: string }) => Promise<number>, args: string[], env: Record<string, string>): Promise<{ code: number; lines: string[]; text: string }> {
|
|
151
|
+
const lines: string[] = []
|
|
152
|
+
const code = await run(args, { env, out: (line) => void lines.push(line), cwd: scratch })
|
|
153
|
+
return { code, lines, text: lines.join('\n') }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The generated project, whose package.json holds the operator's npm scripts. */
|
|
157
|
+
const projectRoot = join(import.meta.dirname, '..', '..', '..')
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* A command exactly as the operator runs it: `npm run <script> -- <args>` in
|
|
161
|
+
* the project, as a process of its own, through the script name, cli.js and
|
|
162
|
+
* its argument parser. The process is given the deployment's settings. cli.js
|
|
163
|
+
* reads the project's .env for any setting its environment does not hold, so
|
|
164
|
+
* every name .env or .env.example sets is passed as well, empty unless the
|
|
165
|
+
* deployment sets it: what the project's own .env holds never reaches the
|
|
166
|
+
* deployment under test.
|
|
167
|
+
*/
|
|
168
|
+
async function npmRun(script: string, args: string[], env: Record<string, string>): Promise<{ code: number | null; lines: string[]; text: string }> {
|
|
169
|
+
const named = ['.env', '.env.example'].flatMap((file) => (existsSync(join(projectRoot, file)) ? [...readFileSync(join(projectRoot, file), 'utf8').matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)].map((match) => match[1]!) : []))
|
|
170
|
+
// A command that hangs is stopped before the test that ran it times out, so no process outlives the test. npm passes the signal on to the command it runs, and the code is then null.
|
|
171
|
+
const child = spawn('npm', ['run', '--silent', script, '--', ...args], { cwd: projectRoot, env: { ...process.env, ...Object.fromEntries(named.map((name) => [name, ''])), ...env }, stdio: ['ignore', 'pipe', 'pipe'], timeout: 90_000 })
|
|
172
|
+
let output = ''
|
|
173
|
+
child.stdout.on('data', (chunk: Buffer) => void (output += chunk.toString('utf8')))
|
|
174
|
+
child.stderr.on('data', (chunk: Buffer) => void (output += chunk.toString('utf8')))
|
|
175
|
+
const [code] = (await once(child, 'close')) as [number | null]
|
|
176
|
+
const lines = output.split('\n').filter((line) => line !== '')
|
|
177
|
+
return { code, lines, text: lines.join('\n') }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Every file under a folder with its digest, so two moments of a folder can be compared. */
|
|
181
|
+
function digestsOf(folder: string): Record<string, string> {
|
|
182
|
+
const out: Record<string, string> = {}
|
|
183
|
+
const walk = (dir: string, prefix: string): void => {
|
|
184
|
+
if (!existsSync(dir)) return
|
|
185
|
+
for (const name of readdirSync(dir).sort()) {
|
|
186
|
+
const path = join(dir, name)
|
|
187
|
+
if (statSync(path).isDirectory()) walk(path, `${prefix}${name}/`)
|
|
188
|
+
else out[`${prefix}${name}`] = createHash('sha256').update(readFileSync(path)).digest('hex')
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
walk(folder, '')
|
|
192
|
+
return out
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Every document of every collection of a database, as text. */
|
|
196
|
+
async function databaseText(uri: string, name: string): Promise<string> {
|
|
197
|
+
const client = await MongoClient.connect(uri)
|
|
198
|
+
try {
|
|
199
|
+
const db = client.db(name)
|
|
200
|
+
const out: string[] = []
|
|
201
|
+
for (const { name: collection } of (await db.listCollections().toArray()).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
202
|
+
const documents = await db.collection(collection).find({}).sort({ _id: 1 }).toArray()
|
|
203
|
+
out.push(`${collection}: ${JSON.stringify(documents)}`)
|
|
204
|
+
}
|
|
205
|
+
return out.join('\n')
|
|
206
|
+
} finally {
|
|
207
|
+
await client.close()
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Every record of an exchange's store of one kind, without revisions. */
|
|
212
|
+
async function recordsOf(storage: EpcisExchangeStorage, kind: string): Promise<Array<{ key: string; value: Json }>> {
|
|
213
|
+
return (await storage.list(kind, { limit: 100_000 })).map((held) => ({ key: held.key, value: held.value as Json }))
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** A copy of a package with files changed or removed and its manifest signed again by the exporter, as a package assembled that way would be. */
|
|
217
|
+
async function repackaged(from: string, name: string, change: (folder: string, manifest: EvidencePackageManifest) => void): Promise<string> {
|
|
218
|
+
const folder = join(scratch, name)
|
|
219
|
+
cpSync(from, folder, { recursive: true })
|
|
220
|
+
const manifest = JSON.parse(readFileSync(join(folder, 'manifest.json'), 'utf8')) as EvidencePackageManifest
|
|
221
|
+
change(folder, manifest)
|
|
222
|
+
// The inventory is made to agree with the files as they now are, so the signature is correct for what the folder holds.
|
|
223
|
+
manifest.inventory = manifest.inventory
|
|
224
|
+
.filter((entry) => existsSync(join(folder, entry.path)))
|
|
225
|
+
.map((entry) => {
|
|
226
|
+
const bytes = readFileSync(join(folder, entry.path))
|
|
227
|
+
return { ...entry, byteLength: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') }
|
|
228
|
+
})
|
|
229
|
+
const key = evidencePackageSigningKey(PrivateKey.fromHex(WALLET_ROOT), manifest.passportId)
|
|
230
|
+
const { value: _value, ...signature } = manifest.signature
|
|
231
|
+
const signed = await signEvidenceManifest({ ...manifest, signature }, { sign: (preimage) => key.sign(preimage).toDER() as number[] })
|
|
232
|
+
writeFileSync(join(folder, 'manifest.json'), JSON.stringify(signed, null, 2))
|
|
233
|
+
return folder
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Every file of a folder as bytes, for a search. */
|
|
237
|
+
function everyFile(folder: string): Array<[string, Buffer]> {
|
|
238
|
+
return Object.keys(digestsOf(folder)).map((path) => [path, readFileSync(join(folder, path))])
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** The forms a secret is passed around in. */
|
|
242
|
+
const formsOf = (secret: string): string[] => [secret, encodeURIComponent(secret), Buffer.from(secret).toString('base64'), Buffer.from(secret).toString('base64url'), Buffer.from(secret).toString('hex')]
|
|
243
|
+
|
|
244
|
+
/* ---------------------------------- state -------------------------------- */
|
|
245
|
+
|
|
246
|
+
let mongoA: MongoMemoryServer
|
|
247
|
+
let mongoB: MongoMemoryServer
|
|
248
|
+
let indexA: DevIndex
|
|
249
|
+
let indexB: DevIndex
|
|
250
|
+
let source: FixtureSource
|
|
251
|
+
let guard: NetworkGuard | undefined
|
|
252
|
+
let b: Deployment | undefined
|
|
253
|
+
let envA: Record<string, string>
|
|
254
|
+
let envB: Record<string, string>
|
|
255
|
+
|
|
256
|
+
/** What A held and answered, kept in memory after A is gone, to hold B against. */
|
|
257
|
+
const kept = {
|
|
258
|
+
passports: [] as Array<{ profile: string; passportId: string; product: Json; reading: PassportReading; authorised: AuthorisedReading }>,
|
|
259
|
+
imports: [] as Array<{ importId: string; record: Json; original: Uint8Array; sha256: string; mediaType: string }>,
|
|
260
|
+
associations: [] as Array<{ key: string; value: Json }>,
|
|
261
|
+
observations: [] as Array<{ key: string; value: Json }>,
|
|
262
|
+
resolutions: [] as Array<{ key: string; value: Json }>,
|
|
263
|
+
pull: undefined as { pull: Json; pages: Json[] } | undefined,
|
|
264
|
+
conflict: undefined as Json | undefined,
|
|
265
|
+
conflictId: '',
|
|
266
|
+
cursor: [] as string[],
|
|
267
|
+
ownerTiers: [] as string[],
|
|
268
|
+
upload: { requestId: 'exit-line-1', bytes: new Uint8Array(0), importId: '', receivedAt: '' },
|
|
269
|
+
}
|
|
270
|
+
const numbers: Record<string, unknown> = {}
|
|
271
|
+
const report = { first: undefined as RestoreReport | undefined }
|
|
272
|
+
|
|
273
|
+
const seven = (): Json[] => Array.from({ length: 7 }, (_, index) => objectEvent(index + 1, [item(`EXIT-${index + 1}`)]))
|
|
274
|
+
|
|
275
|
+
const shared = (over: Record<string, string>): Record<string, string> => ({
|
|
276
|
+
NETWORK: 'main',
|
|
277
|
+
PASSPORT_HOST: 'passports.example.com',
|
|
278
|
+
GS1_PREFIX: '952',
|
|
279
|
+
LIVE_PUBLISHING: 'false',
|
|
280
|
+
AUTH_SECRET,
|
|
281
|
+
BRAND_ROOT_SECRET: BRAND_SECRET,
|
|
282
|
+
MANAGED_IDENTITY_SECRET: IDENTITY_SECRET,
|
|
283
|
+
INDEX_SUBMIT_TOKEN: 'dev-submit-token',
|
|
284
|
+
INDEX_CALLBACK_TOKEN: 'dev-callback-token',
|
|
285
|
+
DPP_GS1_ARTEFACTS_DIR: gs1Dir(),
|
|
286
|
+
DPP_GS1_ARTEFACTS_OFFLINE: 'true',
|
|
287
|
+
EPCIS_SOURCES: 'supplier-a',
|
|
288
|
+
EPCIS_SOURCE_SUPPLIER_A_URL: source.baseUrl,
|
|
289
|
+
EPCIS_SOURCE_SUPPLIER_A_LOCAL_TEST: 'true',
|
|
290
|
+
...over,
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
beforeAll(async () => {
|
|
294
|
+
mongoA = await MongoMemoryServer.create()
|
|
295
|
+
indexA = await startDevIndex({ publisherKey: PUBLISHER_KEY, network: 'main' })
|
|
296
|
+
// The third page request is answered 503, once: the pull below is interrupted after two pages.
|
|
297
|
+
source = await startEpcisSource(seven(), { requireAuthorization: `Bearer ${SOURCE_SECRET}`, failRequest: (n) => (n === 3 ? 503 : undefined) })
|
|
298
|
+
envA = shared({ MONGO_URL: mongoA.getUri(), MONGO_DB: 'deployment_a', INDEX_URL: indexA.url, EPCIS_SOURCE_SUPPLIER_A_BEARER_TOKEN: SOURCE_SECRET })
|
|
299
|
+
}, 180_000)
|
|
300
|
+
|
|
301
|
+
afterAll(async () => {
|
|
302
|
+
guard?.restore()
|
|
303
|
+
await b?.close().catch(() => undefined)
|
|
304
|
+
await source?.close()
|
|
305
|
+
await indexA?.close().catch(() => undefined)
|
|
306
|
+
await indexB?.close().catch(() => undefined)
|
|
307
|
+
await mongoA?.stop().catch(() => undefined)
|
|
308
|
+
await mongoB?.stop().catch(() => undefined)
|
|
309
|
+
// The record of the run, when one was asked for, beside the other evidence of the repository.
|
|
310
|
+
const recordPath = process.env.DPP_EXIT_EXERCISE_RECORD
|
|
311
|
+
if (recordPath != null && recordPath !== '' && numbers.completed === true) {
|
|
312
|
+
mkdirSync(dirname(recordPath), { recursive: true })
|
|
313
|
+
writeFileSync(recordPath, `${JSON.stringify(numbers.record, null, 2)}\n`)
|
|
314
|
+
}
|
|
315
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
316
|
+
}, 120_000)
|
|
317
|
+
|
|
318
|
+
describe('the exit exercise', () => {
|
|
319
|
+
it('builds deployment A: two sector passports with restricted parts, two source scopes that share an event identifier, a decided conflict and an interrupted pull', async () => {
|
|
320
|
+
const a = await start(envA)
|
|
321
|
+
try {
|
|
322
|
+
expect(a.platform.db).toBeDefined()
|
|
323
|
+
expect(a.exchange.storageKind).toBe('mongodb')
|
|
324
|
+
expect(a.platform.profiles.source).toBe('package')
|
|
325
|
+
expect(a.platform.wallet.identityKey).toBe(PUBLISHER_KEY)
|
|
326
|
+
const party = a.platform.parties.brand('dev-brand')
|
|
327
|
+
await a.platform.store.saveBrand({ id: 'dev-brand', name: 'Development brand', identityKey: party.identityKey, did: party.did, createdAt: '2026-03-01T00:00:00.000Z' })
|
|
328
|
+
|
|
329
|
+
for (const [profile, serial] of [
|
|
330
|
+
['eu-battery@2', 'EXIT-BAT-0001'],
|
|
331
|
+
['eu-textile@2', 'EXIT-TEX-0001'],
|
|
332
|
+
] as const) {
|
|
333
|
+
const example = (await a.get(`/api/profiles/${ref(profile)}`)).body.examples[0] as { itemReference: string; serial: string; passportId: string; product: Json }
|
|
334
|
+
const swap = (value: string): string => value.replaceAll(example.serial, serial)
|
|
335
|
+
const product = JSON.parse(swap(JSON.stringify(example.product))) as Json
|
|
336
|
+
// A restricted property carries a value that is nowhere else, so a search can tell where it went.
|
|
337
|
+
if (profile === 'eu-battery@2') product['eubat:manufacturerIdentifier'] = `${RESTRICTED}-BAT`
|
|
338
|
+
else (product['oec:hasOperatorInformation'] as Json)['gs1:organizationName'] = `${RESTRICTED}-TEX`
|
|
339
|
+
const passportId = swap(example.passportId)
|
|
340
|
+
const issued = await a.post('/api/brands/dev-brand/passports', { profile, itemReference: example.itemReference, serial, product })
|
|
341
|
+
expect(issued.status, issued.text).toBe(200)
|
|
342
|
+
expect(issued.body).toMatchObject({ passportId, profile })
|
|
343
|
+
expect(issued.text).not.toContain(RESTRICTED)
|
|
344
|
+
const reading = (await a.get(`/api/verify?passportId=${ref(passportId)}`)).body as PassportReading
|
|
345
|
+
expect(reading.payloadChecks).toHaveLength(1)
|
|
346
|
+
expect(reading.payloadChecks[0]!.publicView.status).toBe('pass')
|
|
347
|
+
const authorised = (await a.post(`/api/passports/${ref(passportId)}/authorised-view`, {})).body as AuthorisedReading
|
|
348
|
+
expect(authorised.ownerTier.status).toBe('pass')
|
|
349
|
+
expect(authorised.authorisedView.status).toBe('pass')
|
|
350
|
+
expect(authorised.product).toEqual(product)
|
|
351
|
+
kept.passports.push({ profile, passportId, product, reading, authorised })
|
|
352
|
+
const journal = (await a.platform.store.getPassport(passportId))!
|
|
353
|
+
kept.ownerTiers.push(...journal.states.map((state) => state.ownerTier!.ciphertext))
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// The identifier host answers from the journal on MongoDB as it does from memory: an item with its passport page, its GTIN and a serial nobody issued with the product page, and a GTIN with no passport with nothing.
|
|
357
|
+
const itemPath = new URL(kept.passports[0]!.passportId).pathname
|
|
358
|
+
const gtinPath = itemPath.slice(0, itemPath.indexOf('/21/'))
|
|
359
|
+
for (const [path, status, location] of [
|
|
360
|
+
[itemPath, 307, `/passport${itemPath}`],
|
|
361
|
+
[gtinPath, 307, `/passport${gtinPath}`],
|
|
362
|
+
[`${gtinPath}/21/NOBODY-ISSUED-THIS`, 307, `/passport${gtinPath}`],
|
|
363
|
+
[`/01/${mintGtin('952', '999999999')}`, 404, null],
|
|
364
|
+
] as const) {
|
|
365
|
+
const answer = await fetch(`${a.base}${path}`, { redirect: 'manual' })
|
|
366
|
+
expect(answer.status, path).toBe(status)
|
|
367
|
+
expect(answer.headers.get('location'), path).toBe(location)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// A file under the default scope, the request a client will make again in B.
|
|
371
|
+
kept.upload.bytes = utf8(JSON.stringify(epcisDocument([objectEvent(11, [item('EXIT-LINE-11')]), objectEvent(12, [item('EXIT-LINE-11'), item('EXIT-LINE-12')])])))
|
|
372
|
+
const uploaded = await a.upload(`/api/epcis/imports?requestId=${kept.upload.requestId}&filename=line.jsonld`, kept.upload.bytes)
|
|
373
|
+
expect(uploaded.status).toBe(201)
|
|
374
|
+
kept.upload.importId = uploaded.body.record.importId
|
|
375
|
+
kept.upload.receivedAt = uploaded.body.record.receivedAt
|
|
376
|
+
|
|
377
|
+
// One event identifier with two bodies under one scope: a conflict, which is decided with both observations kept.
|
|
378
|
+
await a.upload('/api/epcis/imports?requestId=exit-body-1', utf8(JSON.stringify(epcisDocument([objectEvent(20, [item('EXIT-20')])]))))
|
|
379
|
+
const second = await a.upload('/api/epcis/imports?requestId=exit-body-2', utf8(JSON.stringify(epcisDocument([objectEvent(20, [item('EXIT-20')], { disposition: 'in_transit' })]))))
|
|
380
|
+
kept.conflictId = second.body.record.events[0].conflict.conflictId as string
|
|
381
|
+
const decided = await a.post(`/api/epcis/conflicts/${ref(kept.conflictId)}/resolutions`, { decision: 'The later reading stands. Both are kept.', disposition: 'all-retained', decidedAt: '2026-03-10T00:00:00.000Z' })
|
|
382
|
+
expect(decided.status).toBe(201)
|
|
383
|
+
|
|
384
|
+
// The interrupted pull: two pages of four are acknowledged, then the source stops answering.
|
|
385
|
+
const stopped = await a.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
|
|
386
|
+
expect(stopped.body).toMatchObject({ outcome: 'source-unavailable', reason: 'http-error', status: 503, completion: 'failed', exhausted: false, events: { total: 4, new: 4 } })
|
|
387
|
+
|
|
388
|
+
// A second source scope that uses an event identifier the first one holds, with another body. Under its own scope it is simply that source's event.
|
|
389
|
+
const other = await a.upload('/api/epcis/imports?requestId=exit-b-1&sourceId=supplier-b', utf8(JSON.stringify(epcisDocument([objectEvent(1, [item('EXIT-1')], { bizStep: 'shipping' })]))))
|
|
390
|
+
expect(other.status).toBe(201)
|
|
391
|
+
expect(other.body.record).toMatchObject({ sourceId: 'supplier-b', state: 'evaluated', events: [{ arrival: 'new' }] })
|
|
392
|
+
expect((await recordsOf(a.exchange.storage, EPCIS_RECORD_KINDS.observation)).filter((held) => held.value.identity === eventId(1)).map((held) => held.value.sourceId).sort()).toEqual(['supplier-a', 'supplier-b'])
|
|
393
|
+
|
|
394
|
+
// What A holds, kept to hold B against.
|
|
395
|
+
const listed = (await a.get('/api/epcis/imports?limit=200')).body.imports as Array<{ importId: string }>
|
|
396
|
+
for (const { importId } of listed) {
|
|
397
|
+
const record = (await a.get(`/api/epcis/imports/${ref(importId)}`)).body as Json
|
|
398
|
+
const original = await a.get(`/api/epcis/imports/${ref(importId)}/original`)
|
|
399
|
+
expect(original.headers.get('x-content-sha256')).toBe(sha256(original.bytes))
|
|
400
|
+
kept.imports.push({ importId, record, original: original.bytes, sha256: sha256(original.bytes), mediaType: original.headers.get('content-type')! })
|
|
401
|
+
}
|
|
402
|
+
expect(kept.imports).toHaveLength(6)
|
|
403
|
+
kept.associations = await recordsOf(a.exchange.storage, EPCIS_RECORD_KINDS.association)
|
|
404
|
+
kept.observations = await recordsOf(a.exchange.storage, EPCIS_RECORD_KINDS.observation)
|
|
405
|
+
kept.resolutions = await recordsOf(a.exchange.storage, EPCIS_RECORD_KINDS.resolution)
|
|
406
|
+
kept.pull = (await a.get('/api/epcis/sources/supplier-a/pulls/all')).body
|
|
407
|
+
expect(kept.pull!.pull).toMatchObject({ status: 'failed', pagesAcknowledged: 2 })
|
|
408
|
+
expect(kept.pull!.pull.cursor).toBeDefined()
|
|
409
|
+
kept.conflict = (await a.get(`/api/epcis/conflicts/${ref(kept.conflictId)}`)).body
|
|
410
|
+
expect(kept.conflict).toMatchObject({ state: 'resolved' })
|
|
411
|
+
expect((kept.conflict!.observations as unknown[]).length).toBe(2)
|
|
412
|
+
// The cursor A holds: the address of the next page, with the token in it. It may not leave by default. The fixture's token is two
|
|
413
|
+
// characters, too short to search for by itself, so the search is for every text of the cursor that is long enough to mean something.
|
|
414
|
+
const texts: string[] = []
|
|
415
|
+
const collect = (value: unknown): void => {
|
|
416
|
+
if (typeof value === 'string') texts.push(value)
|
|
417
|
+
else if (value !== null && typeof value === 'object') Object.values(value).forEach(collect)
|
|
418
|
+
}
|
|
419
|
+
collect(kept.pull!.pull.cursor)
|
|
420
|
+
kept.cursor = [...new Set(texts.filter((text) => text.length >= 8 && !/^\d{4}-\d{2}-\d{2}T/.test(text)))]
|
|
421
|
+
expect(kept.cursor.some((text) => text.includes('nextPageToken='))).toBe(true)
|
|
422
|
+
expect(await checkEpcisExchangeInvariants(a.exchange.storage, { associations: true })).toEqual([])
|
|
423
|
+
} finally {
|
|
424
|
+
await a.close()
|
|
425
|
+
}
|
|
426
|
+
})
|
|
427
|
+
|
|
428
|
+
it('exports A with the operator\'s command, in both forms, and neither holds a key or a credential', async () => {
|
|
429
|
+
// The package everything below is restored from is written by `npm run export`, the command the documentation gives, as its own process.
|
|
430
|
+
const authorised = await npmRun('export', ['--out', AUTHORISED], envA)
|
|
431
|
+
expect(authorised.code, authorised.text).toBe(0)
|
|
432
|
+
expect(authorised.text).toContain(`Authorised export written to ${AUTHORISED}`)
|
|
433
|
+
expect(authorised.text).toContain(`Exporter identity key, which a restore is given: ${PUBLISHER_KEY}`)
|
|
434
|
+
// The command says when the signature is the test wallet's, which anyone can make.
|
|
435
|
+
expect(authorised.text).toMatch(/signed by the test wallet, whose key is public/)
|
|
436
|
+
// An option the command does not take stops it before anything is opened or written, through the same script.
|
|
437
|
+
const unknown = await npmRun('export', ['--out', join(scratch, 'never-written'), '--no-such-option'], envA)
|
|
438
|
+
expect(unknown.code, unknown.text).toBe(2)
|
|
439
|
+
expect(unknown.text).toMatch(/^usage: export --out <folder>/m)
|
|
440
|
+
const unknownProfile = await command(runExportCommand, ['--out', join(scratch, 'never-written'), '--custody-profile', 'managed-custody@99'], envA)
|
|
441
|
+
expect(unknownProfile).toMatchObject({ code: 1, text: expect.stringContaining('not-selected') })
|
|
442
|
+
expect(existsSync(join(scratch, 'never-written'))).toBe(false)
|
|
443
|
+
expect(authorised.text).not.toContain(SOURCE_SECRET)
|
|
444
|
+
// An export never overwrites: the same folder is refused the second time.
|
|
445
|
+
const again = await command(runExportCommand, ['--out', AUTHORISED], envA)
|
|
446
|
+
expect(again.code).toBe(1)
|
|
447
|
+
expect(again.text).toMatch(/^Refused \(destination-not-empty\)/)
|
|
448
|
+
|
|
449
|
+
// The public form, with one source scope named as publishable. No other scope and no operational record goes with it.
|
|
450
|
+
const selected = await command(runExportCommand, ['--out', MANAGED_RECOVERY, '--custody-profile', 'managed-custody@3'], envA)
|
|
451
|
+
expect(selected.code, selected.text).toBe(0)
|
|
452
|
+
const open = await command(runExportCommand, ['--out', PUBLIC, '--custody-profile', 'managed-custody@3', '--public', '--public-source', 'supplier-b'], envA)
|
|
453
|
+
expect(open.code, open.text).toBe(0)
|
|
454
|
+
|
|
455
|
+
const manifest = JSON.parse(readFileSync(join(AUTHORISED, 'manifest.json'), 'utf8')) as EvidencePackageManifest
|
|
456
|
+
const descriptor = JSON.parse(readFileSync(join(AUTHORISED, 'application/application-export.json'), 'utf8')) as ApplicationExportDescriptor
|
|
457
|
+
expect(manifest.disclosure).toEqual({ scope: 'all-tiers', recoveryBackup: true })
|
|
458
|
+
expect(manifest.exporter.id).toBe(PUBLISHER_KEY)
|
|
459
|
+
expect(manifest.passportId).toMatch(/^urn:bsv:dpp:evidence-export:sha256:[0-9a-f]{64}$/)
|
|
460
|
+
expect(manifest.profiles).toEqual(['eu-battery@2', 'eu-textile@2'])
|
|
461
|
+
expect(descriptor).toMatchObject({ access: 'authorised-recovery', selection: 'all-passports', profiles: { root: 'profiles', carried: ['eu-battery@2', 'eu-textile@2'], named: [] }, epcis: { root: 'epcis', access: 'authorised-recovery', scopes: ['supplier-a', 'supplier-b', 'upload'], cursors: 'excluded' }, records: { brands: 1, offers: 0, claims: 0 } })
|
|
462
|
+
expect(descriptor.passports.map((passport) => passport.index.form)).toEqual(['package', 'package'])
|
|
463
|
+
expect(descriptor.passports.map((passport) => passport.bindingDigest).sort()).toEqual(CURRENT_SECTOR_BINDINGS.map((entry) => entry.bindingDigest).sort())
|
|
464
|
+
// The source is described so that it can be configured again, and its credential is only said to exist.
|
|
465
|
+
expect(descriptor.epcis.sources).toEqual([{ sourceId: 'supplier-a', baseUrl: source.baseUrl, permittedOrigins: [source.origin], localTest: true, repeatListParameters: false, credentialConfigured: true, credentialScheme: 'bearer' }])
|
|
466
|
+
// GS1's files are named by address and digest in the manifest, and are in no file of either package.
|
|
467
|
+
for (const artefact of EPCIS_GS1_ARTEFACTS) {
|
|
468
|
+
expect(manifest.completeness.withheld).toContain(`provisioned-by-destination ${artefact.uri} sha256:${artefact.sha256} bytes:${artefact.byteLength}`)
|
|
469
|
+
for (const folder of [AUTHORISED, PUBLIC]) expect(Object.values(digestsOf(folder))).not.toContain(artefact.sha256)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const publicManifest = JSON.parse(readFileSync(join(PUBLIC, 'manifest.json'), 'utf8')) as EvidencePackageManifest
|
|
473
|
+
const publicDescriptor = JSON.parse(readFileSync(join(PUBLIC, 'application/application-export.json'), 'utf8')) as ApplicationExportDescriptor
|
|
474
|
+
expect(publicManifest.profiles).toContain('managed-custody@3')
|
|
475
|
+
expect(publicManifest.disclosure).toEqual({ scope: 'public', recoveryBackup: false })
|
|
476
|
+
expect(publicDescriptor).toMatchObject({ access: 'public-evidence', epcis: { access: 'public-evidence', scopes: ['supplier-b'], cursors: 'excluded' }, records: { brands: 0, offers: 0, claims: 0 } })
|
|
477
|
+
expect(publicDescriptor.epcis.sources).toBeUndefined()
|
|
478
|
+
const publicPaths = Object.keys(digestsOf(PUBLIC))
|
|
479
|
+
expect(publicPaths.some((path) => path.endsWith('/journal.json') || path.startsWith('application/brands/') || path.startsWith('epcis/records/import/') || path.startsWith('epcis/records/pull'))).toBe(false)
|
|
480
|
+
expect(publicPaths.filter((path) => path.startsWith('epcis/originals/'))).toHaveLength(1)
|
|
481
|
+
expect(publicPaths.some((path) => path.startsWith('profiles/eu-battery@2/'))).toBe(true)
|
|
482
|
+
|
|
483
|
+
// Every byte of the public package is searched for what a public package may never hold.
|
|
484
|
+
const forbiddenInPublic = [
|
|
485
|
+
...formsOf(`${RESTRICTED}-BAT`),
|
|
486
|
+
...formsOf(`${RESTRICTED}-TEX`),
|
|
487
|
+
...formsOf(SOURCE_SECRET),
|
|
488
|
+
`Bearer ${SOURCE_SECRET}`,
|
|
489
|
+
...[BRAND_SECRET, IDENTITY_SECRET, AUTH_SECRET, WALLET_ROOT, 'dev-submit-token', 'dev-callback-token'].flatMap(formsOf),
|
|
490
|
+
// Cursor material and where the source was read from.
|
|
491
|
+
...kept.cursor.flatMap(formsOf),
|
|
492
|
+
'nextPageToken',
|
|
493
|
+
source.origin,
|
|
494
|
+
new URL(source.origin).host,
|
|
495
|
+
// The sealed owner tiers, in the form the journal keeps them and as bytes.
|
|
496
|
+
...kept.ownerTiers,
|
|
497
|
+
...kept.ownerTiers.map((ciphertext) => Buffer.from(ciphertext, 'base64').toString('hex')),
|
|
498
|
+
// Who signed in. The brand's label is not searched for: every state names its actor's key by it, on chain, so it is public by the record model.
|
|
499
|
+
developer.email,
|
|
500
|
+
// The file a client uploaded under another scope, and the requests that bind them.
|
|
501
|
+
'line.jsonld',
|
|
502
|
+
kept.upload.requestId,
|
|
503
|
+
]
|
|
504
|
+
const publicFiles = everyFile(PUBLIC)
|
|
505
|
+
for (const needle of forbiddenInPublic) {
|
|
506
|
+
const found = publicFiles.filter(([, bytes]) => bytes.includes(Buffer.from(needle, 'utf8'))).map(([path]) => path)
|
|
507
|
+
expect(found, `the public package holds ${needle.slice(0, 24)}`).toEqual([])
|
|
508
|
+
}
|
|
509
|
+
for (const ciphertext of kept.ownerTiers) expect(publicFiles.filter(([, bytes]) => bytes.includes(Buffer.from(ciphertext, 'base64')))).toEqual([])
|
|
510
|
+
|
|
511
|
+
// The authorised package holds restricted records, sealed as they were, and still no key, credential or cursor.
|
|
512
|
+
const authorisedFiles = everyFile(AUTHORISED)
|
|
513
|
+
for (const needle of [...formsOf(SOURCE_SECRET), ...[BRAND_SECRET, IDENTITY_SECRET, AUTH_SECRET, WALLET_ROOT, 'dev-submit-token', 'dev-callback-token'].flatMap(formsOf), ...kept.cursor.flatMap(formsOf), 'nextPageToken', `${RESTRICTED}-BAT`, `${RESTRICTED}-TEX`]) {
|
|
514
|
+
const found = authorisedFiles.filter(([, bytes]) => bytes.includes(Buffer.from(needle, 'utf8'))).map(([path]) => path)
|
|
515
|
+
expect(found, `the authorised package holds ${needle.slice(0, 24)}`).toEqual([])
|
|
516
|
+
}
|
|
517
|
+
// The owner tiers travel as the ciphertext the journal holds, and nowhere as what they seal.
|
|
518
|
+
expect(authorisedFiles.filter(([, bytes]) => bytes.includes(Buffer.from(kept.ownerTiers[0]!, 'utf8'))).map(([path]) => path)).toHaveLength(1)
|
|
519
|
+
|
|
520
|
+
numbers.export = {
|
|
521
|
+
authorised: { files: authorisedFiles.length, bytes: authorisedFiles.reduce((sum, [, bytes]) => sum + bytes.byteLength, 0), inventoryEntries: manifest.inventory.length, withheldLines: manifest.completeness.withheld.length, absentLines: manifest.completeness.absent.length, snapshotDeclarations: manifest.completeness.snapshots.length },
|
|
522
|
+
public: { files: publicFiles.length, bytes: publicFiles.reduce((sum, [, bytes]) => sum + bytes.byteLength, 0), inventoryEntries: publicManifest.inventory.length, valuesSearchedFor: forbiddenInPublic.length + kept.ownerTiers.length },
|
|
523
|
+
}
|
|
524
|
+
})
|
|
525
|
+
|
|
526
|
+
it('switches A off, so that nothing can be read from it', async () => {
|
|
527
|
+
const uri = mongoA.getUri()
|
|
528
|
+
const indexUrl = indexA.url
|
|
529
|
+
await indexA.close()
|
|
530
|
+
await mongoA.stop()
|
|
531
|
+
await expect(MongoClient.connect(uri, { serverSelectionTimeoutMS: 1_000 })).rejects.toThrow()
|
|
532
|
+
await expect(fetch(`${indexUrl}/health`)).rejects.toThrow()
|
|
533
|
+
// The API of A was stopped when it had been built; the export ran against its stores with nothing else at work.
|
|
534
|
+
numbers.disabled = { database: 'stopped', index: 'stopped', api: 'stopped' }
|
|
535
|
+
})
|
|
536
|
+
|
|
537
|
+
it('refuses what a restore must refuse, by name, before anything is written', async () => {
|
|
538
|
+
// A database and folders that hold nothing, on a server of their own: each refusal below must leave them so.
|
|
539
|
+
mongoB = await MongoMemoryServer.create()
|
|
540
|
+
const fresh = (name: string, over: Record<string, string> = {}): Record<string, string> => {
|
|
541
|
+
const { INDEX_SUBMIT_TOKEN: _submit, INDEX_CALLBACK_TOKEN: _callback, ...rest } = shared({ MONGO_URL: mongoB.getUri(), MONGO_DB: `refusal_${name}`, EPCIS_STORAGE: 'file', EPCIS_STORAGE_DIR: join(scratch, `refusal-${name}`, 'epcis'), PROFILE_BUNDLE_DIR: join(scratch, `refusal-${name}`, 'profiles'), ...over })
|
|
542
|
+
return rest
|
|
543
|
+
}
|
|
544
|
+
const untouched = async (name: string): Promise<void> => {
|
|
545
|
+
expect(Object.keys(digestsOf(join(scratch, `refusal-${name}`, 'profiles'))), `${name}: the profile folder`).toEqual([])
|
|
546
|
+
const store = Object.keys(digestsOf(join(scratch, `refusal-${name}`, 'epcis')))
|
|
547
|
+
expect(store.filter((path) => !path.endsWith('.lock') && !/^(format|store)\.json$/.test(path)), `${name}: the EPCIS folder`).toEqual([])
|
|
548
|
+
const text = await databaseText(mongoB.getUri(), `refusal_${name}`)
|
|
549
|
+
expect(text, `${name}: the database`).not.toMatch(/"passportId"|"requestId"/)
|
|
550
|
+
}
|
|
551
|
+
const refusals: Record<string, string> = {}
|
|
552
|
+
const refused = async (name: string, folder: string, code: string, detail: RegExp, over: Record<string, string> = {}, args: string[] = []): Promise<void> => {
|
|
553
|
+
const answer = await command(runRestoreCommand, ['--from', folder, '--exporter-key', PUBLISHER_KEY, ...args], fresh(name, over))
|
|
554
|
+
expect(answer.code, answer.text).toBe(1)
|
|
555
|
+
expect(answer.lines[0], answer.text).toMatch(new RegExp(`^Refused \\(${code}\\): `))
|
|
556
|
+
expect(answer.text).toMatch(detail)
|
|
557
|
+
expect(answer.text).toContain('Nothing was written.')
|
|
558
|
+
await untouched(name)
|
|
559
|
+
refusals[name] = answer.lines[0]!.slice(0, answer.lines[0]!.indexOf(':'))
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// 1. A substituted, more permissive profile under a correct exporter signature: the rules are dropped and a restricted property is made public.
|
|
563
|
+
let substituteDigest = ''
|
|
564
|
+
const substituted = await repackaged(AUTHORISED, 'substituted', (folder) => {
|
|
565
|
+
const at = join(folder, 'profiles/eu-battery@2/binding.json')
|
|
566
|
+
const binding = JSON.parse(readFileSync(at, 'utf8')) as { validation: { steps: string[] }; access: { public: string[] } }
|
|
567
|
+
binding.validation.steps = binding.validation.steps.filter((step) => step !== 'shacl')
|
|
568
|
+
binding.access.public.push('eubat:manufacturerIdentifier')
|
|
569
|
+
const bytes = utf8(JSON.stringify(binding, null, 2))
|
|
570
|
+
substituteDigest = profileBindingDigest(bytes)
|
|
571
|
+
writeFileSync(at, bytes)
|
|
572
|
+
// The bundle's own descriptor is made to agree, as whoever built such a package would make it.
|
|
573
|
+
const descriptorAt = join(folder, 'profiles/profile-bundle.json')
|
|
574
|
+
const bundle = JSON.parse(readFileSync(descriptorAt, 'utf8')) as { profiles: Array<{ profile: string; bindingDigest: string }> }
|
|
575
|
+
bundle.profiles.find((entry) => entry.profile === 'eu-battery@2')!.bindingDigest = substituteDigest
|
|
576
|
+
writeFileSync(descriptorAt, JSON.stringify(bundle))
|
|
577
|
+
})
|
|
578
|
+
await refused('substituted', substituted, 'profile-refused', /bundle-binding-substituted/)
|
|
579
|
+
// Trusting the substitute's digest does not let it take the place of the profile the records declare and this deployment knows.
|
|
580
|
+
await refused('substituted-trusted', substituted, 'profile-refused', /bundle-binding-substituted/, { TRUSTED_BINDING_DIGESTS: substituteDigest })
|
|
581
|
+
// The exporter's signature is not the question: under another key than the one expected, the same genuine package is refused too.
|
|
582
|
+
await refused('other-exporter', AUTHORISED, 'exporter-unexpected', /expects the exporter/, {}, ['--exporter-key', PrivateKey.fromHex('77'.repeat(32)).toPublicKey().toString()])
|
|
583
|
+
|
|
584
|
+
// 2. A package whose pull checkpoint stands on an import it does not carry.
|
|
585
|
+
const epcisJson = <T>(folder: string, path: string): T => JSON.parse(readFileSync(join(folder, 'epcis', path), 'utf8')) as T
|
|
586
|
+
type SnapshotDescriptor = { access: string; format: string; version: string; snapshot: { snapshotId: string }; inventory: Array<{ path: string; kind: string; sha256: string; byteLength: number }>; scopes: Array<{ sourceId: string; originals: number; imports: number; observations: number; resolutions: number }> }
|
|
587
|
+
/** Remove records from the snapshot and make its descriptor an honest account of what is left: the files, the counts and the identity. */
|
|
588
|
+
const withoutRecords = (folder: string, removed: (entry: { path: string; kind: string }, value: Json | undefined) => boolean): void => {
|
|
589
|
+
const descriptor = epcisJson<SnapshotDescriptor>(folder, 'epcis-recovery.json')
|
|
590
|
+
const gone = descriptor.inventory.filter((entry) => removed(entry, entry.kind === 'original' ? undefined : epcisJson<Json>(folder, entry.path)))
|
|
591
|
+
for (const entry of gone) {
|
|
592
|
+
const value = entry.kind === 'original' ? undefined : epcisJson<Json>(folder, entry.path)
|
|
593
|
+
const scope = descriptor.scopes.find((candidate) => candidate.sourceId === value?.sourceId)
|
|
594
|
+
if (scope != null && entry.kind === 'import') scope.imports -= 1
|
|
595
|
+
if (scope != null && entry.kind === 'observation') scope.observations -= 1
|
|
596
|
+
rmSync(join(folder, 'epcis', entry.path))
|
|
597
|
+
}
|
|
598
|
+
descriptor.inventory = descriptor.inventory.filter((entry) => !gone.includes(entry))
|
|
599
|
+
descriptor.snapshot.snapshotId = sha256(canonicalJson({ access: descriptor.access, format: descriptor.format, inventory: descriptor.inventory, version: descriptor.version }))
|
|
600
|
+
writeFileSync(join(folder, 'epcis/epcis-recovery.json'), canonicalJson(descriptor))
|
|
601
|
+
const application = JSON.parse(readFileSync(join(folder, 'application/application-export.json'), 'utf8')) as ApplicationExportDescriptor
|
|
602
|
+
application.epcis.snapshotId = descriptor.snapshot.snapshotId
|
|
603
|
+
writeFileSync(join(folder, 'application/application-export.json'), canonicalJson(application))
|
|
604
|
+
}
|
|
605
|
+
const secondPage = kept.pull!.pages[1]!.importId as string
|
|
606
|
+
const noCheckpointImport = await repackaged(AUTHORISED, 'checkpoint-omitted', (folder) => withoutRecords(folder, (entry, value) => (entry.kind === 'import' && value!.importId === secondPage) || (entry.kind === 'observation' && value!.importId === secondPage)))
|
|
607
|
+
await refused('checkpoint-omitted', noCheckpointImport, 'epcis-refused', /checkpoint-imports-omitted/)
|
|
608
|
+
|
|
609
|
+
// 3. A package whose conflict decision names an observation it does not carry.
|
|
610
|
+
const decidedBetween = (kept.resolutions[0]!.value.observations as Array<{ sequence: number; importId: string }>)[1]!
|
|
611
|
+
const noObservation = await repackaged(AUTHORISED, 'resolution-omitted', (folder) => withoutRecords(folder, (entry, value) => entry.kind === 'observation' && value!.importId === decidedBetween.importId && value!.sequence === decidedBetween.sequence))
|
|
612
|
+
await refused('resolution-omitted', noObservation, 'epcis-refused', /resolution-observations-omitted/)
|
|
613
|
+
|
|
614
|
+
// 4. An altered original. One bit is changed: under the genuine manifest the file is not the one listed, and under a manifest signed again for the changed bytes the snapshot's own descriptor refuses it.
|
|
615
|
+
const original = `epcis/originals/${kept.imports[0]!.sha256}`
|
|
616
|
+
const flip = (folder: string): void => {
|
|
617
|
+
const bytes = readFileSync(join(folder, original))
|
|
618
|
+
bytes[20] = bytes[20]! ^ 1
|
|
619
|
+
writeFileSync(join(folder, original), bytes)
|
|
620
|
+
}
|
|
621
|
+
const alteredOnly = join(scratch, 'altered')
|
|
622
|
+
cpSync(AUTHORISED, alteredOnly, { recursive: true })
|
|
623
|
+
flip(alteredOnly)
|
|
624
|
+
await refused('altered', alteredOnly, 'file-altered', new RegExp(original.replaceAll('/', '\\/')))
|
|
625
|
+
await refused('altered-resigned', await repackaged(AUTHORISED, 'altered-resigned', flip), 'epcis-refused', /descriptor-inventory-mismatch/)
|
|
626
|
+
|
|
627
|
+
// 5. An incomplete package, named for what it lacks: a file gone from the folder, and a journal a package was assembled without.
|
|
628
|
+
const journal = `passports/${sha256(kept.passports[0]!.passportId)}/journal.json`
|
|
629
|
+
const lacking = join(scratch, 'lacking')
|
|
630
|
+
cpSync(AUTHORISED, lacking, { recursive: true })
|
|
631
|
+
rmSync(join(lacking, journal))
|
|
632
|
+
await refused('lacking', lacking, 'package-incomplete', new RegExp(journal.replaceAll('/', '\\/')))
|
|
633
|
+
await refused('lacking-resigned', await repackaged(AUTHORISED, 'lacking-resigned', (folder) => rmSync(join(folder, journal))), 'package-incomplete', new RegExp(`does not carry the journal of ${kept.passports[0]!.passportId.replaceAll('/', '\\/')}`))
|
|
634
|
+
|
|
635
|
+
// 6. The public package is not a recovery backup.
|
|
636
|
+
await refused('custody-edition', AUTHORISED, 'not-selected', /managed-custody@3/, {}, ['--require-custody-profile', 'managed-custody@3'])
|
|
637
|
+
await refused('public', PUBLIC, 'not-a-recovery-package', /public disclosure/)
|
|
638
|
+
|
|
639
|
+
// 7. A file nobody listed is not carried along.
|
|
640
|
+
const extra = join(scratch, 'extra')
|
|
641
|
+
cpSync(AUTHORISED, extra, { recursive: true })
|
|
642
|
+
writeFileSync(join(extra, 'application/notes.txt'), 'not part of the export')
|
|
643
|
+
await refused('extra', extra, 'file-unlisted', /application\/notes\.txt/)
|
|
644
|
+
|
|
645
|
+
numbers.refusals = refusals
|
|
646
|
+
}, 240_000)
|
|
647
|
+
|
|
648
|
+
it('restores into deployment B with another storage adapter and another profile resolver, and a second restore changes nothing', async () => {
|
|
649
|
+
indexB = await startDevIndex({ publisherKey: PUBLISHER_KEY, network: 'main' })
|
|
650
|
+
// B's settings: its own database and index, the file-system adapter for the exchange, the bundle resolver for profiles.
|
|
651
|
+
// The source's credential is not configured yet. It is not in the package, and the operator provides it separately, below.
|
|
652
|
+
envB = shared({ MONGO_URL: mongoB.getUri(), MONGO_DB: 'deployment_b', INDEX_URL: indexB.url, EPCIS_STORAGE: 'file', EPCIS_STORAGE_DIR: join(scratch, 'b-epcis-store'), PROFILE_BUNDLE_DIR: join(scratch, 'b-profile-bundle') })
|
|
653
|
+
|
|
654
|
+
// From here on the network is B's own services and the one EPCIS source. Anything else is refused and written down.
|
|
655
|
+
guard = guardNetwork()
|
|
656
|
+
for (const address of [mongoB.getUri().replace('mongodb://', 'http://'), indexB.url, source.origin]) guard.allow(portOf(address))
|
|
657
|
+
// The guard is shown to work before it is relied on: the hosts profile files and contexts are published at are out of reach.
|
|
658
|
+
for (const host of ['https://ref.gs1.org/', 'https://w3id.org/', 'https://www.w3.org/', 'https://schema.org/']) await expect(fetch(host)).rejects.toThrow(/kept to this test's own services/)
|
|
659
|
+
await expect(fetch(`${indexA.url}/health`)).rejects.toThrow(/kept to this test's own services/)
|
|
660
|
+
expect(guard.attempts.splice(0)).toHaveLength(5)
|
|
661
|
+
|
|
662
|
+
const reportFile = join(scratch, 'restore-report.json')
|
|
663
|
+
const restored = await command(runRestoreCommand, ['--from', MANAGED_RECOVERY, '--require-custody-profile', 'managed-custody@3', '--exporter-key', PUBLISHER_KEY, '--report', reportFile], envB)
|
|
664
|
+
expect(restored.code, restored.text).toBe(0)
|
|
665
|
+
const first = JSON.parse(readFileSync(reportFile, 'utf8')) as RestoreReport
|
|
666
|
+
report.first = first
|
|
667
|
+
expect(first).toMatchObject({
|
|
668
|
+
outcome: 'restored',
|
|
669
|
+
exporter: PUBLISHER_KEY,
|
|
670
|
+
passports: { written: kept.passports.map((passport) => passport.passportId).sort(), unchanged: [] },
|
|
671
|
+
records: { brands: { written: 1, unchanged: 0 } },
|
|
672
|
+
profiles: { resolver: 'bundle', folder: join(scratch, 'b-profile-bundle'), filesUnchanged: 0, registered: CURRENT_SECTOR_BINDINGS.map((entry) => ({ profile: entry.profile, bindingDigest: entry.bindingDigest })), notRegistered: [] },
|
|
673
|
+
epcis: { outcome: 'restored', sourceIds: ['supplier-a', 'supplier-b', 'upload'], written: { originals: 6, imports: 6, resolutions: 1, pulls: 1, pullPages: 2 }, relocations: 6 },
|
|
674
|
+
index: { rebuilt: true, announced: 2, admitted: 2, duplicate: 0, notAnnounced: [] },
|
|
675
|
+
readings: { compared: 2, same: 2, different: [], notCompared: [] },
|
|
676
|
+
attention: [],
|
|
677
|
+
})
|
|
678
|
+
expect(first.epcis!.written.observations).toBe(kept.observations.length)
|
|
679
|
+
expect(first.epcis!.associationsRebuilt).toBe(kept.associations.length)
|
|
680
|
+
expect(first.profiles.filesWritten).toBeGreaterThan(10)
|
|
681
|
+
// The report says what the operator still provides, and names the credential the package did not carry.
|
|
682
|
+
expect(first.provisionSeparately.join('\n')).toMatch(/The EPCIS source supplier-a: it is configured here at the address it had\. Its bearer credential is not configured here: set it before a pull\./)
|
|
683
|
+
expect(first.provisionSeparately.join('\n')).toMatch(/wallet's own recovery/)
|
|
684
|
+
expect(restored.text).not.toContain(SOURCE_SECRET)
|
|
685
|
+
|
|
686
|
+
// The same package restored again, this time with `npm run restore`, the command the documentation gives, as its own process: nothing is written anywhere.
|
|
687
|
+
// That process is outside this one's network guard. It reaches B's database and index, which is all the first restore, inside the guard, reached.
|
|
688
|
+
const before = { database: await databaseText(mongoB.getUri(), 'deployment_b'), store: digestsOf(join(scratch, 'b-epcis-store')), bundle: digestsOf(join(scratch, 'b-profile-bundle')) }
|
|
689
|
+
const again = await npmRun('restore', ['--from', AUTHORISED, '--exporter-key', PUBLISHER_KEY, '--report', reportFile], envB)
|
|
690
|
+
expect(again.code, again.text).toBe(0)
|
|
691
|
+
expect(again.text).toMatch(/^Restore unchanged: export /m)
|
|
692
|
+
expect(again.text).not.toContain(SOURCE_SECRET)
|
|
693
|
+
// A key that is not one is refused by the command's own argument check, before the package is read.
|
|
694
|
+
const malformed = await npmRun('restore', ['--from', AUTHORISED, '--exporter-key', 'not-a-key'], envB)
|
|
695
|
+
expect(malformed.code, malformed.text).toBe(2)
|
|
696
|
+
expect(malformed.text).toMatch(/^--exporter-key is a compressed public key/m)
|
|
697
|
+
const second = JSON.parse(readFileSync(reportFile, 'utf8')) as RestoreReport
|
|
698
|
+
expect(second).toMatchObject({
|
|
699
|
+
outcome: 'unchanged',
|
|
700
|
+
passports: { written: [], unchanged: kept.passports.map((passport) => passport.passportId).sort() },
|
|
701
|
+
records: { brands: { written: 0, unchanged: 1 } },
|
|
702
|
+
profiles: { filesWritten: 0, filesUnchanged: first.profiles.filesWritten },
|
|
703
|
+
epcis: { outcome: 'unchanged', written: { originals: 0, imports: 0, observations: 0, resolutions: 0, pulls: 0, pullPages: 0 } },
|
|
704
|
+
index: { announced: 2, admitted: 0, duplicate: 2 },
|
|
705
|
+
readings: { compared: 2, same: 2 },
|
|
706
|
+
attention: [],
|
|
707
|
+
})
|
|
708
|
+
expect(await databaseText(mongoB.getUri(), 'deployment_b')).toBe(before.database)
|
|
709
|
+
expect(digestsOf(join(scratch, 'b-epcis-store'))).toEqual(before.store)
|
|
710
|
+
expect(digestsOf(join(scratch, 'b-profile-bundle'))).toEqual(before.bundle)
|
|
711
|
+
// The exported package is unchanged by being restored from.
|
|
712
|
+
expect(await command(runRestoreCommand, ['--from', AUTHORISED, '--exporter-key', PUBLISHER_KEY], envB)).toMatchObject({ code: 0 })
|
|
713
|
+
numbers.restore = { first: { outcome: first.outcome, passports: first.passports.written.length, epcis: first.epcis!.written, relocations: first.epcis!.relocations, associationsRebuilt: first.epcis!.associationsRebuilt, profileFiles: first.profiles.filesWritten, statesAnnounced: first.index.announced, readingsSame: first.readings.same }, second: { outcome: second.outcome, statesAlreadyHeld: second.index.duplicate } }
|
|
714
|
+
}, 240_000)
|
|
715
|
+
|
|
716
|
+
it('proves in B the same passports, with the same reports, from the bundle and with the upstream hosts out of reach', async () => {
|
|
717
|
+
b = await start(envB, (port) => guard!.allow(port))
|
|
718
|
+
expect(b.exchange.storageKind).toBe('file')
|
|
719
|
+
expect(b.platform.profiles.source).toBe('bundle')
|
|
720
|
+
expect(b.platform.profiles.refusals).toEqual([])
|
|
721
|
+
expect(b.lines).toContain('EPCIS recovery: nothing was left unfinished.')
|
|
722
|
+
expect((await b.get('/api/operations')).body.profiles).toMatchObject({ source: 'bundle', engine: { available: true, kind: 'in-process' }, refused: [] })
|
|
723
|
+
|
|
724
|
+
for (const passport of kept.passports) {
|
|
725
|
+
const reading = (await b.get(`/api/verify?passportId=${ref(passport.passportId)}`)).body as PassportReading
|
|
726
|
+
// The same native findings: every check of the report, by name, status and reason, and the report's own limits.
|
|
727
|
+
expect(reading.checks).toEqual(passport.reading.checks)
|
|
728
|
+
expect(reading.report.checks).toEqual(passport.reading.report.checks)
|
|
729
|
+
expect(reading.report.limits).toEqual(passport.reading.report.limits)
|
|
730
|
+
expect(reading.lineage).toEqual(passport.reading.lineage)
|
|
731
|
+
// The same profile validation outcome, finding for finding.
|
|
732
|
+
expect(reading.payloadChecks).toEqual(passport.reading.payloadChecks)
|
|
733
|
+
expect(reading.product).toEqual(passport.reading.product)
|
|
734
|
+
expect(reading.product!.bindingDigest).toBe(CURRENT_SECTOR_BINDINGS.find((entry) => entry.profile === passport.profile)!.bindingDigest)
|
|
735
|
+
|
|
736
|
+
// The holder's view: the stored ciphertext is the one the state commits to, and only then is it opened and checked whole.
|
|
737
|
+
const authorised = (await b.post(`/api/passports/${ref(passport.passportId)}/authorised-view`, {})).body as AuthorisedReading
|
|
738
|
+
expect(authorised).toEqual(passport.authorised)
|
|
739
|
+
expect(authorised.ownerTier).toMatchObject({ status: 'pass' })
|
|
740
|
+
// The profile's answer and the commitment's are two findings. A passing validation is never the statement about the commitment.
|
|
741
|
+
expect(authorised.authorisedView.summary).toMatch(/This is not a statement about the on-chain commitment/)
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// The identity rule is enforced here as it was there: a document about another item is refused for this passport, and nothing is signed.
|
|
745
|
+
const battery = kept.passports[0]!
|
|
746
|
+
const other = JSON.parse(JSON.stringify(battery.product).replaceAll('EXIT-BAT-0001', 'EXIT-BAT-0002')) as Json
|
|
747
|
+
const wrong = await b.post(`/api/passports/${ref(battery.passportId)}/update`, { product: other })
|
|
748
|
+
expect(wrong.status).toBe(409)
|
|
749
|
+
expect(wrong.body).toMatchObject({ error: 'product-invalid', cause: 'product-identity-mismatch' })
|
|
750
|
+
expect((await b.platform.store.getPassport(battery.passportId))!.states).toHaveLength(1)
|
|
751
|
+
numbers.passports = { verified: kept.passports.length, checksPerReport: kept.passports.map((passport) => passport.reading.report.checks.length), payloadChecks: kept.passports.map((passport) => passport.reading.payloadChecks.length) }
|
|
752
|
+
}, 120_000)
|
|
753
|
+
|
|
754
|
+
it('proves in B the EPCIS exchange: exact originals, rebuilt associations and every durable record as it was', async () => {
|
|
755
|
+
const storage = b!.exchange.storage
|
|
756
|
+
expect(await checkEpcisExchangeInvariants(storage, { associations: true })).toEqual([])
|
|
757
|
+
|
|
758
|
+
// Exact originals, byte for byte, under the media type they arrived with.
|
|
759
|
+
for (const held of kept.imports) {
|
|
760
|
+
const original = await b!.get(`/api/epcis/imports/${ref(held.importId)}/original`)
|
|
761
|
+
expect(original.status).toBe(200)
|
|
762
|
+
expect(Buffer.from(original.bytes).equals(Buffer.from(held.original)), held.importId).toBe(true)
|
|
763
|
+
expect(original.headers.get('x-content-sha256')).toBe(held.sha256)
|
|
764
|
+
expect(original.headers.get('content-type')).toBe(held.mediaType)
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Every import record as it was: its identity, its request binding, its receipt time, its results. Two things may differ, and no other: where the
|
|
768
|
+
// bytes are kept, which the destination names for itself, and the page token a page was asked for with, which is cursor material and was left out.
|
|
769
|
+
const withoutToken = (query: unknown): unknown => {
|
|
770
|
+
if (query === null || typeof query !== 'object') return query
|
|
771
|
+
const { nextPageToken: _token, ...rest } = query as Json
|
|
772
|
+
return rest
|
|
773
|
+
}
|
|
774
|
+
const withoutLocation = ({ bytesRef: _bytesRef, ...record }: Json): Json => {
|
|
775
|
+
const location = record.sourceLocation as Json | undefined
|
|
776
|
+
return location?.query == null ? record : { ...record, sourceLocation: { ...location, query: withoutToken(location.query) } }
|
|
777
|
+
}
|
|
778
|
+
const pageWithoutToken = (page: Json): Json => (page.query == null ? page : { ...page, query: withoutToken(page.query) })
|
|
779
|
+
for (const held of kept.imports) {
|
|
780
|
+
const record = (await b!.get(`/api/epcis/imports/${ref(held.importId)}`)).body as Json
|
|
781
|
+
expect(withoutLocation(record)).toEqual(withoutLocation(held.record))
|
|
782
|
+
expect(record).toMatchObject({ importId: held.importId, requestId: held.record.requestId, requestDigest: held.record.requestDigest, receivedAt: held.record.receivedAt, sourceId: held.record.sourceId })
|
|
783
|
+
}
|
|
784
|
+
expect((await b!.get('/api/epcis/imports?limit=200')).body.imports).toHaveLength(kept.imports.length)
|
|
785
|
+
|
|
786
|
+
// The associations were rebuilt, not carried, and are the ones A held.
|
|
787
|
+
expect(await recordsOf(storage, EPCIS_RECORD_KINDS.association)).toEqual(kept.associations)
|
|
788
|
+
expect(await recordsOf(storage, EPCIS_RECORD_KINDS.observation)).toEqual(kept.observations)
|
|
789
|
+
expect(await recordsOf(storage, EPCIS_RECORD_KINDS.resolution)).toEqual(kept.resolutions)
|
|
790
|
+
|
|
791
|
+
// The conflict is decided here as it was, by the same decision at the same time, with both observations kept.
|
|
792
|
+
expect((await b!.get(`/api/epcis/conflicts/${ref(kept.conflictId)}`)).body).toEqual(kept.conflict)
|
|
793
|
+
// The two scopes that share an event identifier were not merged.
|
|
794
|
+
expect((await recordsOf(storage, EPCIS_RECORD_KINDS.observation)).filter((held) => held.value.identity === eventId(1)).map((held) => held.value.sourceId).sort()).toEqual(['supplier-a', 'supplier-b'])
|
|
795
|
+
|
|
796
|
+
// The pull: its definition, its bounds, its checkpoint and its pages are the ones A held. Its cursor was left out.
|
|
797
|
+
const pull = (await b!.get('/api/epcis/sources/supplier-a/pulls/all')).body as { pull: Json; pages: Json[] }
|
|
798
|
+
const withoutCursor = ({ cursor: _cursor, ...record }: Json): Json => record
|
|
799
|
+
expect(pull.pull.cursor).toBeUndefined()
|
|
800
|
+
expect(withoutCursor(pull.pull)).toEqual(withoutCursor(kept.pull!.pull))
|
|
801
|
+
expect(pull.pull).toMatchObject({ status: 'failed', pagesAcknowledged: 2 })
|
|
802
|
+
expect(pull.pages).toEqual(kept.pull!.pages.map(pageWithoutToken))
|
|
803
|
+
expect(JSON.stringify(pull)).not.toContain('nextPageToken')
|
|
804
|
+
|
|
805
|
+
// A client that never heard its answer sends the request again, to B: the same import, the same receipt time, no new receipt.
|
|
806
|
+
const retried = await b!.upload(`/api/epcis/imports?requestId=${kept.upload.requestId}&filename=line.jsonld`, kept.upload.bytes)
|
|
807
|
+
expect(retried.status).toBe(200)
|
|
808
|
+
expect(retried.body).toMatchObject({ outcome: 'retained', replayed: true, record: { importId: kept.upload.importId, receivedAt: kept.upload.receivedAt } })
|
|
809
|
+
expect((await b!.get('/api/epcis/imports?limit=200')).body.imports).toHaveLength(kept.imports.length)
|
|
810
|
+
// The same request identifier with other content still conflicts, and the restored import stands.
|
|
811
|
+
const changed = await b!.upload(`/api/epcis/imports?requestId=${kept.upload.requestId}&filename=line.jsonld`, utf8(JSON.stringify(epcisDocument([objectEvent(13, [item('EXIT-LINE-13')])]))))
|
|
812
|
+
expect(changed.status).toBe(409)
|
|
813
|
+
expect(changed.body).toMatchObject({ error: 'request-conflict', existingImportId: kept.upload.importId, kept: false })
|
|
814
|
+
expect((await b!.get('/api/epcis/imports?limit=200')).body.imports).toHaveLength(kept.imports.length)
|
|
815
|
+
numbers.epcis = { originalsByteForByte: kept.imports.length, importRecordsEqual: kept.imports.length, associationsEqual: kept.associations.length, observationsEqual: kept.observations.length, decisionsEqual: kept.resolutions.length, pullPagesEqual: kept.pull!.pages.length, sourceScopes: 3 }
|
|
816
|
+
}, 120_000)
|
|
817
|
+
|
|
818
|
+
it('resumes the interrupted pull only once its credential is provided again, and replays safely without its cursor', async () => {
|
|
819
|
+
const requestsBefore = source.requests.length
|
|
820
|
+
// Without the credential the source refuses, and the pull is where it was.
|
|
821
|
+
const without = await b!.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
|
|
822
|
+
expect(without.status).toBe(200)
|
|
823
|
+
expect(without.body.exhausted).toBe(false)
|
|
824
|
+
expect(without.body.events.new).toBe(0)
|
|
825
|
+
expect((await b!.get('/api/epcis/sources/supplier-a/pulls/all')).body.pull).toMatchObject({ pagesAcknowledged: 2 })
|
|
826
|
+
expect((await b!.get('/api/epcis/sources')).body).toMatchObject([{ sourceId: 'supplier-a', credentialConfigured: false }])
|
|
827
|
+
const refusedRequests = source.requests.length - requestsBefore
|
|
828
|
+
|
|
829
|
+
// The operator provides the credential, in B's own settings, and starts the API again. The address is the one the pull is bound to, and declaring it changes nothing.
|
|
830
|
+
await b!.close()
|
|
831
|
+
b = undefined
|
|
832
|
+
envB = { ...envB, EPCIS_SOURCE_SUPPLIER_A_BEARER_TOKEN: SOURCE_SECRET }
|
|
833
|
+
const remap = await command(runRemapCommand, ['--source', 'supplier-a'], envB)
|
|
834
|
+
expect(remap.code, remap.text).toBe(0)
|
|
835
|
+
expect(remap.text).toMatch(/all: already bound to .*; cursor none\./)
|
|
836
|
+
b = await start(envB, (port) => guard!.allow(port))
|
|
837
|
+
expect((await b.get('/api/epcis/sources')).body).toMatchObject([{ sourceId: 'supplier-a', credentialConfigured: true, credentialScheme: 'bearer' }])
|
|
838
|
+
|
|
839
|
+
const asked = source.requests.length
|
|
840
|
+
const resumed = await b.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
|
|
841
|
+
expect(resumed.status).toBe(200)
|
|
842
|
+
expect(resumed.body).toMatchObject({ outcome: 'ok', reason: 'exhausted', exhausted: true })
|
|
843
|
+
// With no cursor to use, the pass was asked for again from its retained bounds: from the first page, in order, with none skipped.
|
|
844
|
+
const offsets = source.requests.slice(asked).map((request) => (request.query.nextPageToken == null ? 0 : Number(Buffer.from(request.query.nextPageToken, 'base64url').toString())))
|
|
845
|
+
expect(offsets).toEqual([0, 2, 4, 6])
|
|
846
|
+
// What was already held was recognised as it arrived: three events are new, and the pages A acknowledged made no second import.
|
|
847
|
+
expect(resumed.body.events).toMatchObject({ new: 3, conflict: 0 })
|
|
848
|
+
const state = (await b.get('/api/epcis/sources/supplier-a/pulls/all')).body as { pull: Json; pages: Json[] }
|
|
849
|
+
expect(state.pull).toMatchObject({ status: 'exhausted', sourceId: 'supplier-a', pullId: kept.pull!.pull.pullId })
|
|
850
|
+
expect(state.pages.slice(0, 2).map((page) => ({ importId: page.importId, sha256: page.sha256, sequence: page.sequence, page: page.page, receivedAt: page.receivedAt }))).toEqual(kept.pull!.pages.map((page) => ({ importId: page.importId, sha256: page.sha256, sequence: page.sequence, page: page.page, receivedAt: page.receivedAt })))
|
|
851
|
+
const pageImports = [...new Set(state.pages.map((page) => page.importId as string))]
|
|
852
|
+
expect(pageImports.slice(0, 2)).toEqual(kept.pull!.pages.map((page) => page.importId))
|
|
853
|
+
expect(pageImports).toHaveLength(4)
|
|
854
|
+
expect((await b.get('/api/epcis/imports?limit=200')).body.imports).toHaveLength(kept.imports.length + 2)
|
|
855
|
+
// Every event of the source is held once under its scope.
|
|
856
|
+
const observed = (await recordsOf(b.exchange.storage, EPCIS_RECORD_KINDS.observation)).filter((held) => held.value.sourceId === 'supplier-a').map((held) => held.value.identity as string)
|
|
857
|
+
expect(observed.sort()).toEqual(Array.from({ length: 7 }, (_, index) => eventId(index + 1)).sort())
|
|
858
|
+
expect(await checkEpcisExchangeInvariants(b.exchange.storage, { associations: true })).toEqual([])
|
|
859
|
+
// The credential went to the source and nowhere else.
|
|
860
|
+
for (const line of b.lines) expect(line).not.toContain(SOURCE_SECRET)
|
|
861
|
+
expect(JSON.stringify(await recordsOf(b.exchange.storage, EPCIS_RECORD_KINDS.pull))).not.toContain(SOURCE_SECRET)
|
|
862
|
+
numbers.pull = { pagesAcknowledgedBeforeExport: 2, requestsRefusedWithoutCredential: refusedRequests, cursor: 'excluded from the package, so the pass replayed from its retained bounds', pageOffsetsAskedForInB: offsets, eventsNewInB: resumed.body.events.new, pageRecordsAfter: state.pages.length, importsThosePagesStandOn: pageImports.length, importsAddedInB: 2 }
|
|
863
|
+
}, 120_000)
|
|
864
|
+
|
|
865
|
+
it('keeps both scopes and the resolved conflict after B restarts and replays its pull', async () => {
|
|
866
|
+
const sharedEvent = (await recordsOf(b!.exchange.storage, EPCIS_RECORD_KINDS.observation))
|
|
867
|
+
.filter((entry) => entry.value.identity === eventId(1))
|
|
868
|
+
expect(sharedEvent).toEqual(kept.observations.filter((entry) => entry.value.identity === eventId(1)))
|
|
869
|
+
expect(sharedEvent.map((entry) => entry.value.sourceId).sort()).toEqual(['supplier-a', 'supplier-b'])
|
|
870
|
+
|
|
871
|
+
const supplierImport = kept.imports.find((entry) => entry.record.sourceId === 'supplier-b')!
|
|
872
|
+
const path = `/api/epcis/imports?sourceId=supplier-b&requestId=${ref(supplierImport.record.requestId as string)}`
|
|
873
|
+
const retried = await b!.upload(path, supplierImport.original)
|
|
874
|
+
expect(retried.status).toBe(200)
|
|
875
|
+
expect(retried.body).toMatchObject({ replayed: true, record: {
|
|
876
|
+
sourceId: 'supplier-b', importId: supplierImport.importId, receivedAt: supplierImport.record.receivedAt,
|
|
877
|
+
requestDigest: supplierImport.record.requestDigest,
|
|
878
|
+
} })
|
|
879
|
+
const otherScope = sharedEvent.find((entry) => entry.value.sourceId === 'supplier-a')!
|
|
880
|
+
const differentBytes = kept.imports.find((entry) => entry.importId === otherScope.value.importId)!.original
|
|
881
|
+
const conflict = await b!.upload(path, differentBytes)
|
|
882
|
+
expect(conflict.status).toBe(409)
|
|
883
|
+
expect(conflict.body).toMatchObject({ error: 'request-conflict', existingImportId: supplierImport.importId, kept: false })
|
|
884
|
+
expect((await b!.get('/api/epcis/imports?limit=200')).body.imports).toHaveLength(kept.imports.length + 2)
|
|
885
|
+
|
|
886
|
+
expect((await b!.get(`/api/epcis/conflicts/${ref(kept.conflictId)}`)).body).toEqual(kept.conflict)
|
|
887
|
+
const decision = kept.resolutions[0]!.value.observations as Array<{ importId: string }>
|
|
888
|
+
expect(new Set(decision.map((entry) => entry.importId)).size).toBe(2)
|
|
889
|
+
for (const { importId } of decision) {
|
|
890
|
+
const original = await b!.get(`/api/epcis/imports/${ref(importId)}/original`)
|
|
891
|
+
expect(original.status).toBe(200)
|
|
892
|
+
expect(original.bytes).toEqual(kept.imports.find((entry) => entry.importId === importId)!.original)
|
|
893
|
+
}
|
|
894
|
+
numbers.afterReplay = { scopedRetry: retried.status, changedBytes: conflict.status, scopesHoldingSharedId: sharedEvent.length, conflictOriginalsRead: decision.length }
|
|
895
|
+
})
|
|
896
|
+
|
|
897
|
+
it('continues an authorised UPDATE in B, which verifies, and made no network attempt beyond its own services', async () => {
|
|
898
|
+
const battery = kept.passports[0]!
|
|
899
|
+
// An explicit passport operation, asked for by a member of the brand that holds the passport. It needs the keys: the brand's, derived from the secret B was
|
|
900
|
+
// given by its operator, and the wallet's, which B holds by the wallet's own recovery. Neither came from the package.
|
|
901
|
+
const product = { ...structuredClone(battery.product), 'gs1:productDescription': [{ '@value': 'Serviced and returned to use', '@language': 'en' }] }
|
|
902
|
+
const updated = await b!.post(`/api/passports/${ref(battery.passportId)}/update`, { product })
|
|
903
|
+
expect(updated.status, updated.text).toBe(200)
|
|
904
|
+
expect(updated.body.states.map((state: Json) => state.op)).toEqual(['ISSUE', 'UPDATE'])
|
|
905
|
+
expect(updated.body.states[1]).toMatchObject({ index: 'admitted', network: 'dry-run' })
|
|
906
|
+
|
|
907
|
+
const reading = (await b!.get(`/api/verify?passportId=${ref(battery.passportId)}`)).body as PassportReading
|
|
908
|
+
expect(reading.lineage.map((state) => state.op)).toEqual(['ISSUE', 'UPDATE'])
|
|
909
|
+
expect(reading.lineage[0]!.txid).toBe(battery.reading.lineage[0]!.txid)
|
|
910
|
+
// The lineage verifies as one: every check answers as it did for the genesis alone, and both payloads pass under the bundle's profile.
|
|
911
|
+
expect(reading.checks.map((check) => [check.name, check.status])).toEqual(battery.reading.checks.map((check) => [check.name, check.status]))
|
|
912
|
+
expect(reading.payloadChecks.map((check) => check.publicView.status)).toEqual(['pass', 'pass'])
|
|
913
|
+
const authorised = (await b!.post(`/api/passports/${ref(battery.passportId)}/authorised-view`, {})).body as AuthorisedReading
|
|
914
|
+
expect(authorised.ownerTier.status).toBe('pass')
|
|
915
|
+
expect(authorised.authorisedView.status).toBe('pass')
|
|
916
|
+
expect(authorised.product).toEqual(product)
|
|
917
|
+
// The other passport was not touched.
|
|
918
|
+
expect((await b!.platform.store.getPassport(kept.passports[1]!.passportId))!.states).toHaveLength(1)
|
|
919
|
+
|
|
920
|
+
// Nothing left B for anywhere but its own database, its own index and the EPCIS source.
|
|
921
|
+
expect(guard!.attempts).toEqual([])
|
|
922
|
+
// A is still gone, and nothing above needed it.
|
|
923
|
+
guard!.restore()
|
|
924
|
+
guard = undefined
|
|
925
|
+
await expect(fetch(`${indexA.url}/health`)).rejects.toThrow()
|
|
926
|
+
|
|
927
|
+
numbers.update = { op: 'UPDATE', states: 2, indexAnswer: updated.body.states[1].index, networkAnswer: updated.body.states[1].network, verified: true }
|
|
928
|
+
numbers.network = { attemptsRefused: 0, permitted: ['deployment B\'s database', 'deployment B\'s index', 'deployment B\'s API', 'the fixture EPCIS source'] }
|
|
929
|
+
numbers.record = {
|
|
930
|
+
check: 'packages/create-dpp-app/template/apps/api/test/exit-exercise.test.ts',
|
|
931
|
+
recordedAt: new Date().toLocaleDateString('en-CA'),
|
|
932
|
+
node: process.version,
|
|
933
|
+
// The generated application is not a checkout. The check that generated it says which source it came from.
|
|
934
|
+
releaseSet: process.env.DPP_EXIT_EXERCISE_RELEASE_SET ?? 'unknown',
|
|
935
|
+
sourceRevision: process.env.DPP_EXIT_EXERCISE_SOURCE_REVISION ?? 'unknown',
|
|
936
|
+
sourceState: process.env.DPP_EXIT_EXERCISE_SOURCE_STATE ?? 'unknown',
|
|
937
|
+
failures: 0,
|
|
938
|
+
exercised: [
|
|
939
|
+
'Deployment A built two passports under eu-battery@2 and eu-textile@2, each with a public and a restricted part, and an EPCIS exchange with three source scopes, two of which share an event identifier, one conflict decided with both observations kept, and a pull interrupted after two of four pages.',
|
|
940
|
+
'A was exported in the authorised form with npm run export, run as its own process, and in the public form with the same command called in the test process, then switched off: its API, its database and its index were stopped.',
|
|
941
|
+
'Eleven packages that must be refused were refused by name with nothing written: a substituted and more permissive profile under a correct exporter signature, with and without its digest trusted, another exporter key, a pull checkpoint without its import, a conflict decision without its observation, an altered original under the genuine and under a re-signed manifest, a missing journal under the genuine and under a re-signed manifest, the public package, and a file the manifest does not list.',
|
|
942
|
+
'The authorised package was restored with the restore command into deployment B, which keeps the exchange in the file-system adapter and resolves profiles from the installed bundle. A second restore, with npm run restore run as its own process, wrote nothing.',
|
|
943
|
+
'In B both passports gave the reports they gave in A, check for check and finding for finding, the holder\'s view opened, and a document about another item was refused for the passport.',
|
|
944
|
+
'In B every original was returned byte for byte, every import record, observation, decision and pull page equalled A\'s, and the associations rebuilt at B equalled the ones A held.',
|
|
945
|
+
'A request A had acknowledged answered the same import in B with no new receipt, and the same request identifier with other content conflicted.',
|
|
946
|
+
'The pull was refused by the source until its credential was configured in B, then replayed from its retained bounds without a cursor and finished with no event held twice.',
|
|
947
|
+
'After B restarted and replayed its pull, the shared identifier still had one observation in each supplier scope. A scoped retry returned its original receipt, changed bytes under that request were refused, and both originals named by the conflict decision remained readable.',
|
|
948
|
+
'An UPDATE of the battery passport was written in B and the two-state lineage verified.',
|
|
949
|
+
],
|
|
950
|
+
numbers: { export: numbers.export, restore: numbers.restore, refusals: numbers.refusals, passports: numbers.passports, epcis: numbers.epcis, pull: numbers.pull, afterReplay: numbers.afterReplay, update: numbers.update, network: numbers.network, disabled: numbers.disabled },
|
|
951
|
+
simulated: [
|
|
952
|
+
'Each index was the reference index\'s code in the test process, over in-memory storage, with its header checks off. It proves no inclusion: every reading in this exercise was made against scripts only, and nothing here is a statement that a state is in a block.',
|
|
953
|
+
'The wallet was the test wallet, with fixed keys and made-up funding. Nothing was sent to a network: each state\'s network answer is dry-run.',
|
|
954
|
+
'Both deployments held the same wallet key and the same secrets for brand and recipient keys, set by the test. That stands in for the wallet\'s own recovery and the operator\'s own handling of secrets. The package carried none of them.',
|
|
955
|
+
'Sign-in was the development session in both deployments. An export carries no account, session or membership.',
|
|
956
|
+
'The EPCIS source was the fixture server of the tests, on the loopback address, with a bearer credential.',
|
|
957
|
+
'MongoDB was a real server for each deployment, started in memory by the test set-up. The pinned GS1 files were provisioned for the test and read offline.',
|
|
958
|
+
],
|
|
959
|
+
limits: {
|
|
960
|
+
reached: 'two passports of one state each, six retained EPCIS documents of at most two events, one pull of four pages. These are the sizes this run used, not a capacity.',
|
|
961
|
+
notExercised: [
|
|
962
|
+
'A TRANSFER and its acceptance record, a lifecycle claim and a hand-on offer: this run held none. apps/api/test/portability.test.ts exports and restores them, with records in memory.',
|
|
963
|
+
'A lineage longer than the bound of the index\'s package. The same test carries a short lineage as the parts of the index\'s complete export; no long one was exported.',
|
|
964
|
+
'A source that moved to another address: the remap command was run against the unchanged address only.',
|
|
965
|
+
'A cursor carried at the operator\'s request (--cursors include).',
|
|
966
|
+
'The validator service as B\'s engine: B validated with the engine in its process.',
|
|
967
|
+
'A persistent index and a header source: inclusion was not checked by either deployment.',
|
|
968
|
+
],
|
|
969
|
+
},
|
|
970
|
+
statement: 'Profile validity is reported apart from the owner-tier check and is never a statement that disclosed data is what a state\'s payload_owner_hash commits to.',
|
|
971
|
+
}
|
|
972
|
+
}, 120_000)
|
|
973
|
+
|
|
974
|
+
it('restores into a deployment that holds none of A\'s keys, which reads every passport and verifies all but the issuer\'s authority, opens no restricted part and refuses an UPDATE by name', async () => {
|
|
975
|
+
// Deployment C is restored from the same package with keys of its own: another wallet root key, and other secrets for its brand and recipient keys.
|
|
976
|
+
// Its index admits states under the publisher key A wrote with, which is public. Nothing that would let C act for A's brand reaches it.
|
|
977
|
+
const indexC = await startDevIndex({ publisherKey: PUBLISHER_KEY, network: 'main' })
|
|
978
|
+
const envC = shared({ MONGO_URL: mongoB.getUri(), MONGO_DB: 'deployment_c', INDEX_URL: indexC.url, EPCIS_STORAGE: 'file', EPCIS_STORAGE_DIR: join(scratch, 'c-epcis-store'), PROFILE_BUNDLE_DIR: join(scratch, 'c-profile-bundle'), WALLET_ROOT_KEY: 'c3'.repeat(32), DPP_TEST_WALLET: '1', BRAND_ROOT_SECRET: 'c1'.repeat(32), MANAGED_IDENTITY_SECRET: 'c2'.repeat(32) })
|
|
979
|
+
let c: Deployment | undefined
|
|
980
|
+
try {
|
|
981
|
+
const reportFile = join(scratch, 'restore-report-c.json')
|
|
982
|
+
const restored = await command(runRestoreCommand, ['--from', AUTHORISED, '--exporter-key', PUBLISHER_KEY, '--report', reportFile], envC)
|
|
983
|
+
// Everything is restored, and the command ends with the code that says the operator has something to do: the passports read differently here, and the report says why.
|
|
984
|
+
expect(restored.code, restored.text).toBe(3)
|
|
985
|
+
const report = JSON.parse(readFileSync(reportFile, 'utf8')) as RestoreReport
|
|
986
|
+
expect(report).toMatchObject({ outcome: 'restored', passports: { written: kept.passports.map((passport) => passport.passportId).sort(), unchanged: [] }, index: { rebuilt: true, announced: 2, admitted: 2 }, readings: { compared: 2, same: 0 } })
|
|
987
|
+
expect(report.provisionSeparately.join('\n')).toMatch(/BRAND_ROOT_SECRET and MANAGED_IDENTITY_SECRET as they were: without them this deployment reads every passport and can write none of them/)
|
|
988
|
+
expect([...report.attention].sort()).toEqual(kept.passports.map((passport) => `${passport.passportId} reads differently here: issuerAuthority: pass where it was exported, fail (authority-unconfirmed) here.`).sort())
|
|
989
|
+
|
|
990
|
+
c = await start(envC)
|
|
991
|
+
expect(c.platform.wallet.identityKey).not.toBe(PUBLISHER_KEY)
|
|
992
|
+
for (const passport of kept.passports) {
|
|
993
|
+
// C verifies the passport: the same lineage, signatures, linkage and payload checks as A. One finding differs. C reads a passport in its own journal
|
|
994
|
+
// as issued by its own key for the brand, and its key is not the one the genesis was signed with, so the issuer's authority is not confirmed here.
|
|
995
|
+
const reading = (await c.get(`/api/verify?passportId=${ref(passport.passportId)}`)).body as PassportReading
|
|
996
|
+
expect(reading.lineage).toEqual(passport.reading.lineage)
|
|
997
|
+
expect(reading.payloadChecks).toEqual(passport.reading.payloadChecks)
|
|
998
|
+
expect(reading.product).toEqual(passport.reading.product)
|
|
999
|
+
expect(reading.checks.map((check) => check.name)).toEqual(passport.reading.checks.map((check) => check.name))
|
|
1000
|
+
const differing = reading.checks.filter((check, at) => JSON.stringify(check) !== JSON.stringify(passport.reading.checks[at]))
|
|
1001
|
+
expect(differing).toEqual([{ name: 'issuerAuthority', label: expect.any(String), status: 'fail', reasonCode: 'authority-unconfirmed' }])
|
|
1002
|
+
expect(passport.reading.checks.find((check) => check.name === 'issuerAuthority')).toMatchObject({ status: 'pass' })
|
|
1003
|
+
|
|
1004
|
+
// C reads the passport as its journal holds it.
|
|
1005
|
+
const view = await c.get(`/api/passports/${ref(passport.passportId)}`)
|
|
1006
|
+
expect(view.status).toBe(200)
|
|
1007
|
+
expect(view.body).toMatchObject({ passportId: passport.passportId, profile: passport.profile, holder: { party: 'brand:dev-brand' } })
|
|
1008
|
+
expect(view.text).not.toContain(RESTRICTED)
|
|
1009
|
+
// The restricted part is held and is the one the state commits to, but it is sealed to A's key. C does not open it, and says so: not checked, never a pass.
|
|
1010
|
+
const authorised = (await c.post(`/api/passports/${ref(passport.passportId)}/authorised-view`, {})).body as AuthorisedReading
|
|
1011
|
+
expect(authorised.ownerTier.status).toBe('pass')
|
|
1012
|
+
expect(authorised.authorisedView.status).toBe('not-checked')
|
|
1013
|
+
expect(authorised.authorisedView.summary).toContain('The wallet for brand:dev-brand could not open the committed restricted part')
|
|
1014
|
+
expect(authorised.product).toBeUndefined()
|
|
1015
|
+
expect(JSON.stringify(authorised)).not.toContain(RESTRICTED)
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// C cannot write. An UPDATE or a RETIRE asked for by a member of the brand is refused by name before anything is signed, and the passport is as it was.
|
|
1019
|
+
const battery = kept.passports[0]!
|
|
1020
|
+
const product = { ...structuredClone(battery.product), 'gs1:productDescription': [{ '@value': 'Serviced and returned to use', '@language': 'en' }] }
|
|
1021
|
+
for (const [path, body] of [['update', { product }], ['retire', { reason: 'end of life' }]] as const) {
|
|
1022
|
+
const refused = await c.post(`/api/passports/${ref(battery.passportId)}/${path}`, body)
|
|
1023
|
+
expect(refused.status, path).toBe(409)
|
|
1024
|
+
expect(refused.body, path).toMatchObject({ error: 'not-the-controller' })
|
|
1025
|
+
expect(refused.body.description, path).toMatch(/the key this deployment derives for brand:dev-brand is another one: it does not hold the secret the passport was written under/)
|
|
1026
|
+
}
|
|
1027
|
+
expect((await c.platform.store.getPassport(battery.passportId))!.states).toHaveLength(1)
|
|
1028
|
+
expect(((await c.get(`/api/verify?passportId=${ref(battery.passportId)}`)).body as PassportReading).lineage).toEqual(battery.reading.lineage)
|
|
1029
|
+
} finally {
|
|
1030
|
+
await c?.close()
|
|
1031
|
+
await indexC.close()
|
|
1032
|
+
}
|
|
1033
|
+
// The record is written only once this, the last step, has passed, and only with the record the UPDATE step assembled.
|
|
1034
|
+
const record = numbers.record as { exercised: string[] } | undefined
|
|
1035
|
+
record?.exercised.push('The same package was restored into deployment C, which holds none of A\'s keys. C verified both passports with every finding as in A except the issuer\'s authority, which it does not confirm, read them, did not open their restricted parts, and refused an UPDATE and a RETIRE by name with nothing written.')
|
|
1036
|
+
numbers.completed = record != null
|
|
1037
|
+
}, 120_000)
|
|
1038
|
+
})
|