@yarkivaev/scada 2.13.0 → 2.14.0
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/index.js +29 -0
- package/package.json +3 -2
- package/src/application/control/controlClient.js +1 -1
- package/src/application/control/createOnlyJSON.js +50 -0
- package/src/application/control/index.js +2 -0
- package/src/application/control/jsonAssignments.js +30 -0
- package/src/application/mcp/loadMetricSeries.js +69 -0
- package/src/application/mcp/locateMachineMetric.js +25 -0
- package/src/application/mcp/metricQueryPorts.js +78 -0
- package/src/application/mcp/parseBearerTokens.js +43 -0
- package/src/application/runtime/assignment.js +4 -1
- package/src/infrastructure/deploy/applyWhenChanged.js +15 -0
- package/src/infrastructure/deploy/deploymentKube.js +35 -0
- package/src/infrastructure/deploy/executeKubeSeed.js +24 -0
- package/src/infrastructure/deploy/executeRelease.js +8 -11
- package/src/infrastructure/deploy/operatePostgresMaintenance.js +85 -0
- package/src/infrastructure/deploy/postgresMaintenancePlan.js +54 -0
- package/src/infrastructure/deploy/postgresRestoreObjects.js +73 -0
- package/src/infrastructure/deploy/preflightKubeStorage.js +76 -0
- package/src/infrastructure/deploy/prepareKubePrerequisites.js +95 -0
- package/src/infrastructure/deploy/verifyCollectorCoverage.js +43 -0
- package/src/infrastructure/deploy/verifyPeerBrokerPerimeter.js +24 -0
- package/src/infrastructure/ingest/mysql40/byteReader.js +51 -0
- package/src/infrastructure/ingest/mysql40/mysql40.js +116 -0
- package/src/infrastructure/ingest/mysql40/packets.js +72 -0
- package/src/infrastructure/ingest/mysql40/resultRows.js +92 -0
- package/src/infrastructure/ingest/mysql40/scramble.js +89 -0
- package/src/infrastructure/ingest/telemetry/edgeTelemetryRuntime.js +83 -0
- package/src/infrastructure/ingest/telemetry/replayStoredTelemetry.js +125 -0
- package/src/infrastructure/management/kubeServiceAccount.js +43 -0
- package/src/infrastructure/management/kubectlPortForward.js +27 -0
- package/src/infrastructure/mdmesh/hmiApplication.js +64 -0
- package/src/infrastructure/mdmesh/hmiControl.js +85 -0
- package/src/infrastructure/mdmesh/hmiFile.js +69 -0
- package/src/infrastructure/mdmesh/hmiMonitor.js +53 -0
- package/src/infrastructure/mdmesh/hmiReconcile.js +170 -0
- package/src/infrastructure/mdmesh/hmiRuntime.js +33 -0
- package/src/infrastructure/mdmesh/index.js +7 -0
- package/src/infrastructure/mdmesh/mdmeshClient.js +72 -0
- package/src/infrastructure/messaging/ownership/edgeSitesFromEnv.js +137 -0
- package/src/infrastructure/messaging/rabbitmq/reconcile.js +71 -12
- package/src/infrastructure/opcua/health.js +91 -0
- package/src/infrastructure/opcua/index.js +1 -0
- package/src/infrastructure/persistence/pg/prepareRuntimeRole.js +67 -0
- package/src/infrastructure/replication/canonicalJSON.js +15 -0
- package/src/infrastructure/replication/postgresSnapshotReplica.js +129 -0
- package/src/infrastructure/replication/postgresSnapshotRuntime.js +40 -0
- package/src/infrastructure/replication/snapshotSync.js +61 -0
- package/src/infrastructure/replication/tableSnapshotFormat.js +50 -0
- package/src/infrastructure/tls/mirrorTLSSecret.js +37 -0
- package/src/infrastructure/tls/mutualJSON.js +79 -0
- package/src/infrastructure/tls/tlsMaterial.js +57 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/AtomicStateFile.scala +7 -0
- package/stream-processing/src/main/scala/scada/processing/infra/state/StateJournal.scala +22 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/HistoryClient.scala +10 -1
- package/stream-processing/src/main/scala/scada/processing/runtime/LiveWorker.scala +70 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/LocalHistory.scala +2 -8
- package/stream-processing/src/main/scala/scada/processing/runtime/StatefulHistory.scala +108 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/TimelinePublication.scala +43 -0
- package/stream-processing/src/main/scala/scada/processing/runtime/WorkerStores.scala +43 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
|
|
3
|
+
const protocol = ['postgres:', 'postgresql:'];
|
|
4
|
+
|
|
5
|
+
function addresses(adminUrl, runtimeUrl, { hosts, port = 5432, database, role }) {
|
|
6
|
+
const admin = new URL(adminUrl);
|
|
7
|
+
const runtime = new URL(runtimeUrl);
|
|
8
|
+
for (const address of [admin, runtime]) {
|
|
9
|
+
if (!protocol.includes(address.protocol) || !hosts.includes(address.hostname) ||
|
|
10
|
+
(address.port || '5432') !== String(port) ||
|
|
11
|
+
decodeURIComponent(address.pathname.slice(1)) !== database || !address.password) {
|
|
12
|
+
throw new Error('Runtime role credentials must address the configured PostgreSQL database');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
if (decodeURIComponent(runtime.username) !== role) {
|
|
16
|
+
throw new Error('Runtime login must use the configured restricted role');
|
|
17
|
+
}
|
|
18
|
+
return { admin, runtime };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function activate(admin, runtime, roleName) {
|
|
22
|
+
const result = await admin.query(
|
|
23
|
+
'SELECT rolcanlogin,rolsuper,rolcreatedb,rolcreaterole,rolreplication,rolbypassrls FROM pg_roles WHERE rolname=$1',
|
|
24
|
+
[roleName]
|
|
25
|
+
);
|
|
26
|
+
const role = result.rows[0];
|
|
27
|
+
if (role && (role.rolsuper || role.rolcreatedb || role.rolcreaterole || role.rolreplication || role.rolbypassrls)) {
|
|
28
|
+
throw new Error('Unexpected privileged runtime role');
|
|
29
|
+
}
|
|
30
|
+
if (role?.rolcanlogin) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
if (!role) {
|
|
34
|
+
const create = await admin.query("SELECT format('CREATE ROLE %I NOLOGIN', $1::text) AS command", [roleName]);
|
|
35
|
+
await admin.query(create.rows[0].command);
|
|
36
|
+
}
|
|
37
|
+
const alter = await admin.query(
|
|
38
|
+
"SELECT format('ALTER ROLE %I LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD %L', $1::text, $2::text) AS command",
|
|
39
|
+
[roleName, decodeURIComponent(runtime.password)]
|
|
40
|
+
);
|
|
41
|
+
await admin.query(alter.rows[0].command);
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Enables a restricted PostgreSQL login and verifies existing credentials without rotating its password. */
|
|
46
|
+
export default async function prepareRuntimeRole(adminUrl, runtimeUrl, settings) {
|
|
47
|
+
const { role, verify, lockKey } = settings;
|
|
48
|
+
const urls = addresses(adminUrl, runtimeUrl, settings);
|
|
49
|
+
const admin = new pg.Client({ connectionString: urls.admin.href, connectionTimeoutMillis: 5000, 'query_timeout': 10000 });
|
|
50
|
+
try {
|
|
51
|
+
await admin.connect();
|
|
52
|
+
await admin.query('SELECT pg_advisory_lock(hashtextextended($1,0))', [lockKey ?? role]);
|
|
53
|
+
const createdLogin = await activate(admin, urls.runtime, role);
|
|
54
|
+
const application = new pg.Client({ connectionString: urls.runtime.href, connectionTimeoutMillis: 5000, 'query_timeout': 5000 });
|
|
55
|
+
try {
|
|
56
|
+
await application.connect();
|
|
57
|
+
if (verify) {
|
|
58
|
+
await verify(application);
|
|
59
|
+
}
|
|
60
|
+
} finally {
|
|
61
|
+
await application.end();
|
|
62
|
+
}
|
|
63
|
+
return { user: role, createdLogin };
|
|
64
|
+
} finally {
|
|
65
|
+
await admin.end();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function canonicalJSON(value) {
|
|
4
|
+
if (Array.isArray(value)) { return `[${value.map(canonicalJSON).join(',')}]`; }
|
|
5
|
+
if (value && typeof value === 'object') {
|
|
6
|
+
return `{${Object.keys(value).sort().map((key) => {
|
|
7
|
+
return `${JSON.stringify(key)}:${canonicalJSON(value[key])}`;
|
|
8
|
+
}).join(',')}}`;
|
|
9
|
+
}
|
|
10
|
+
return JSON.stringify(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function jsonDigest(value) {
|
|
14
|
+
return createHash('sha256').update(canonicalJSON(value)).digest('hex');
|
|
15
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { canonicalJSON } from './canonicalJSON.js';
|
|
2
|
+
|
|
3
|
+
function identifier(name) {
|
|
4
|
+
if (typeof name !== 'string' || !name || name.includes('\0')) { throw new Error('Invalid PostgreSQL identifier'); }
|
|
5
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
async function transaction(pool, begin, operation) {
|
|
9
|
+
const client = await pool.connect();
|
|
10
|
+
try {
|
|
11
|
+
await client.query(begin);
|
|
12
|
+
const result = await operation(client);
|
|
13
|
+
await client.query('COMMIT');
|
|
14
|
+
return result;
|
|
15
|
+
} catch (error) {
|
|
16
|
+
await client.query('ROLLBACK').catch(() => { return undefined; });
|
|
17
|
+
throw error;
|
|
18
|
+
} finally { client.release(); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function validateRows(snapshot) {
|
|
22
|
+
snapshot.schema.forEach(({ table, columns }) => {
|
|
23
|
+
const keys = canonicalJSON(columns.map((column) => { return column.name; }).sort());
|
|
24
|
+
if (snapshot.tables[table].some((row) => { return !row || canonicalJSON(Object.keys(row).sort()) !== keys; })) {
|
|
25
|
+
throw new Error('Snapshot columns do not match');
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function schemaFor(client, namespace, tables) {
|
|
31
|
+
const result = await client.query(`SELECT c.relname AS "table", a.attname AS name,
|
|
32
|
+
pg_catalog.format_type(a.atttypid,a.atttypmod) AS type, NOT a.attnotnull AS nullable
|
|
33
|
+
FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
|
|
34
|
+
JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
|
|
35
|
+
WHERE n.nspname=$1 AND c.relname=ANY($2::text[]) AND a.attnum>0 AND NOT a.attisdropped
|
|
36
|
+
ORDER BY c.relname,a.attnum`, [namespace, tables]);
|
|
37
|
+
return [...tables].sort().map((table) => {
|
|
38
|
+
return { table, columns: result.rows.filter((row) => { return row.table === table; })
|
|
39
|
+
.map(({ name, type, nullable }) => { return { name, type, nullable }; }) };
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function checkpointStatements(table) {
|
|
44
|
+
return {
|
|
45
|
+
latest: `SELECT hash,exported_at AS "exportedAt",imported_at AS "importedAt" FROM ${table} WHERE id=1`,
|
|
46
|
+
ensure: `CREATE TABLE IF NOT EXISTS ${table}
|
|
47
|
+
(id integer PRIMARY KEY CHECK(id=1), hash text NOT NULL, exported_at timestamptz NOT NULL, imported_at timestamptz NOT NULL)`,
|
|
48
|
+
save: `INSERT INTO ${table} (id,hash,exported_at,imported_at)
|
|
49
|
+
VALUES (1,$1,$2,clock_timestamp()) ON CONFLICT(id) DO UPDATE
|
|
50
|
+
SET hash=EXCLUDED.hash,exported_at=EXCLUDED.exported_at,imported_at=EXCLUDED.imported_at
|
|
51
|
+
RETURNING hash,exported_at AS "exportedAt",imported_at AS "importedAt"`
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function tableReader(client, qualified) {
|
|
56
|
+
return async (table) => {
|
|
57
|
+
if (!qualified.has(table)) { throw new Error('Table outside snapshot schema'); }
|
|
58
|
+
const result = await client.query(`SELECT row_to_json(row) AS value FROM ${qualified.get(table)} row`);
|
|
59
|
+
return result.rows.map((row) => { return row.value; });
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function replaceRows(client, snapshot, qualified, { cascade, disableTriggers }) {
|
|
64
|
+
if (disableTriggers) { await client.query('SET LOCAL session_replication_role=replica'); }
|
|
65
|
+
await client.query(`TRUNCATE ${[...qualified.values()].join(',')}${cascade ? ' CASCADE' : ''}`);
|
|
66
|
+
for (const [name, table] of qualified) {
|
|
67
|
+
// Insert in catalog order because later tables can reference earlier tables.
|
|
68
|
+
// eslint-disable-next-line no-await-in-loop
|
|
69
|
+
await client.query(`INSERT INTO ${table} SELECT * FROM json_populate_recordset(NULL::${table}, $1::json)`,
|
|
70
|
+
[JSON.stringify(snapshot.tables[name])]);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Replicate an explicit table catalog and atomically record its checkpoint in PostgreSQL. */
|
|
75
|
+
export function postgresSnapshotReplica({
|
|
76
|
+
namespace = 'public', tables, format, checkpoint, lock, compatible, cascade = false, disableTriggers = false
|
|
77
|
+
}) {
|
|
78
|
+
function qualify(name) { return `${identifier(namespace)}.${identifier(name)}`; }
|
|
79
|
+
if (tables.includes(checkpoint)) { throw new Error('Checkpoint table must be outside snapshot schema'); }
|
|
80
|
+
const qualified = new Map(tables.map((name) => { return [name, qualify(name)]; }));
|
|
81
|
+
const state = checkpointStatements(qualify(checkpoint));
|
|
82
|
+
function schema(client) { return schemaFor(client, namespace, tables); }
|
|
83
|
+
|
|
84
|
+
function exportSnapshot(pool) {
|
|
85
|
+
return transaction(pool, 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY', async (client) => {
|
|
86
|
+
await client.query("SET LOCAL TIME ZONE 'UTC'");
|
|
87
|
+
await client.query("SET LOCAL bytea_output='hex'");
|
|
88
|
+
const localSchema = await schema(client);
|
|
89
|
+
const read = tableReader(client, qualified);
|
|
90
|
+
const rows = [];
|
|
91
|
+
for (const name of tables) {
|
|
92
|
+
// The transaction's PostgreSQL client supports one query at a time.
|
|
93
|
+
// eslint-disable-next-line no-await-in-loop
|
|
94
|
+
rows.push([name, await read(name)]);
|
|
95
|
+
}
|
|
96
|
+
return format.seal({ schema: localSchema, tables: Object.fromEntries(rows) });
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function importSnapshot(pool, input) {
|
|
101
|
+
const snapshot = format.validate(input);
|
|
102
|
+
validateRows(snapshot);
|
|
103
|
+
return transaction(pool, 'BEGIN', async (client) => {
|
|
104
|
+
await client.query('SELECT pg_advisory_xact_lock($1::bigint)', [lock]);
|
|
105
|
+
if (canonicalJSON(await schema(client)) !== canonicalJSON(snapshot.schema)
|
|
106
|
+
|| compatible && !await compatible(snapshot, tableReader(client, qualified))) {
|
|
107
|
+
throw new Error('Snapshot does not match the local PostgreSQL schema or identity');
|
|
108
|
+
}
|
|
109
|
+
await client.query(state.ensure);
|
|
110
|
+
const previous = await client.query(state.latest);
|
|
111
|
+
if (previous.rows[0]?.hash !== snapshot.hash) {
|
|
112
|
+
await replaceRows(client, snapshot, qualified, { cascade, disableTriggers });
|
|
113
|
+
}
|
|
114
|
+
const result = await client.query(state.save, [snapshot.hash, snapshot.createdAt]);
|
|
115
|
+
return result.rows[0];
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function checkpointFor(pool) {
|
|
120
|
+
const result = await transaction(pool, 'BEGIN', async (client) => {
|
|
121
|
+
await client.query('SELECT pg_advisory_xact_lock($1::bigint)', [lock]);
|
|
122
|
+
await client.query(state.ensure);
|
|
123
|
+
return client.query(state.latest);
|
|
124
|
+
});
|
|
125
|
+
return result.rows[0] || null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { schema, exportSnapshot, importSnapshot, checkpointFor };
|
|
129
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import pg from 'pg';
|
|
2
|
+
|
|
3
|
+
function connect({ connectionString, onDatabaseError, poolOptions }) {
|
|
4
|
+
const pool = new pg.Pool({ connectionString, max: 2, options: '-c statement_timeout=20000', connectionTimeoutMillis: 10000, ...poolOptions });
|
|
5
|
+
pool.on('error', () => { onDatabaseError?.(); });
|
|
6
|
+
return pool;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function listen(server, { port, host = '127.0.0.1' }, pool, worker) {
|
|
10
|
+
const number = Number(port);
|
|
11
|
+
if (!Number.isSafeInteger(number) || number < 1 || number > 65535) { throw new Error('PostgreSQL snapshot server port is invalid'); }
|
|
12
|
+
server.listen(number, host);
|
|
13
|
+
function close() { server.close(); }
|
|
14
|
+
async function release() {
|
|
15
|
+
process.off('SIGTERM', close);
|
|
16
|
+
process.off('SIGINT', close);
|
|
17
|
+
if (worker) { await worker.stop(); }
|
|
18
|
+
await pool.end();
|
|
19
|
+
}
|
|
20
|
+
server.once('close', () => { void release(); });
|
|
21
|
+
process.once('SIGTERM', close);
|
|
22
|
+
process.once('SIGINT', close);
|
|
23
|
+
return server;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function servePostgresSnapshot(settings, createServer) {
|
|
27
|
+
const pool = connect(settings);
|
|
28
|
+
try { return listen(createServer(pool), settings, pool); }
|
|
29
|
+
catch (error) { void pool.end(); throw error; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function followPostgresSnapshot(settings, createWorker) {
|
|
33
|
+
const pool = connect(settings);
|
|
34
|
+
try {
|
|
35
|
+
const worker = await createWorker(pool);
|
|
36
|
+
const server = listen(worker.server, settings, pool, worker);
|
|
37
|
+
worker.start();
|
|
38
|
+
return server;
|
|
39
|
+
} catch (error) { await pool.end(); throw error; }
|
|
40
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
|
|
4
|
+
function samples(state) {
|
|
5
|
+
const imported = state.checkpoint ? Date.parse(state.checkpoint.importedAt) / 1000 : 0;
|
|
6
|
+
const exported = state.checkpoint ? Date.parse(state.checkpoint.exportedAt) / 1000 : 0;
|
|
7
|
+
return {
|
|
8
|
+
ready: state.checkpoint ? 1 : 0,
|
|
9
|
+
last_success_timestamp_seconds: imported,
|
|
10
|
+
snapshot_timestamp_seconds: exported,
|
|
11
|
+
snapshot_age_seconds: exported ? Math.max(0, Date.now() / 1000 - exported) : 0,
|
|
12
|
+
sync_errors_total: state.errors,
|
|
13
|
+
last_attempt_success: state.lastAttempt ? 1 : 0,
|
|
14
|
+
tls_renewal_errors_total: state.tlsErrors,
|
|
15
|
+
tls_last_success_timestamp_seconds: state.tlsSuccess
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function status(state, prefix, incoming, response) {
|
|
20
|
+
if (incoming.method !== 'GET') { response.writeHead(405).end(); }
|
|
21
|
+
else if (incoming.url === '/healthz') {
|
|
22
|
+
response.writeHead(state.checkpoint ? 200 : 503, { 'Content-Type': 'application/json' })
|
|
23
|
+
.end(JSON.stringify({ ready: Boolean(state.checkpoint) }));
|
|
24
|
+
} else if (incoming.url === '/metrics') {
|
|
25
|
+
const metrics = Object.entries(samples(state)).map(([name, value]) => { return `${prefix}_${name} ${value}`; });
|
|
26
|
+
response.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4' }).end(`${metrics.join('\n')}\n`);
|
|
27
|
+
} else { response.writeHead(404).end(); }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Readiness follows the local checkpoint. Remote failures are reported separately. */
|
|
31
|
+
export async function snapshotSync({
|
|
32
|
+
checkpoint, fetchSnapshot, applySnapshot, renewTLS, stateFile, interval = 60000, metricPrefix = 'snapshot_replica'
|
|
33
|
+
}) {
|
|
34
|
+
if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/u.test(metricPrefix)) { throw new Error('Invalid replica metric prefix'); }
|
|
35
|
+
const state = { checkpoint: await checkpoint(), errors: 0, lastAttempt: false, tlsErrors: 0, tlsSuccess: 0 };
|
|
36
|
+
const server = createServer((incoming, response) => { status(state, metricPrefix, incoming, response); });
|
|
37
|
+
let timer;
|
|
38
|
+
let stopped = false;
|
|
39
|
+
let running;
|
|
40
|
+
async function update() {
|
|
41
|
+
try {
|
|
42
|
+
state.checkpoint = await applySnapshot(await fetchSnapshot());
|
|
43
|
+
state.lastAttempt = true;
|
|
44
|
+
if (stateFile) { await writeFile(stateFile, JSON.stringify(state.checkpoint), { mode: 0o600 }); }
|
|
45
|
+
} catch { state.errors += 1; state.lastAttempt = false; }
|
|
46
|
+
}
|
|
47
|
+
async function renewal() {
|
|
48
|
+
try {
|
|
49
|
+
if (renewTLS && await renewTLS()) { state.tlsSuccess = Date.now() / 1000; }
|
|
50
|
+
} catch { state.tlsErrors += 1; }
|
|
51
|
+
}
|
|
52
|
+
async function poll() {
|
|
53
|
+
await Promise.all([update(), renewal()]);
|
|
54
|
+
if (!stopped) { timer = setTimeout(() => { running = poll(); }, interval); }
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
server,
|
|
58
|
+
start() { if (!running && !stopped) { running = poll(); } },
|
|
59
|
+
async stop() { stopped = true; clearTimeout(timer); await running; }
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { canonicalJSON, jsonDigest } from './canonicalJSON.js';
|
|
2
|
+
|
|
3
|
+
export const tableSnapshotLimit = 64 * 1024 * 1024;
|
|
4
|
+
|
|
5
|
+
function compareRows(first, second) {
|
|
6
|
+
const before = canonicalJSON(first);
|
|
7
|
+
const after = canonicalJSON(second);
|
|
8
|
+
if (before < after) { return -1; }
|
|
9
|
+
if (before > after) { return 1; }
|
|
10
|
+
return 0;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function fail() { throw new Error('Table snapshot is invalid or incompatible'); }
|
|
14
|
+
|
|
15
|
+
function tableSet(value, names, sortedNames) {
|
|
16
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
17
|
+
|| canonicalJSON(Object.keys(value).sort()) !== sortedNames) { fail(); }
|
|
18
|
+
if (names.some((table) => { return !Array.isArray(value[table]); })) { fail(); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function schemaValid(schema, sortedNames) {
|
|
22
|
+
if (!Array.isArray(schema)
|
|
23
|
+
|| canonicalJSON(schema.map((item) => { return item?.table; }).sort()) !== sortedNames) { fail(); }
|
|
24
|
+
if (schema.some((item) => { return !Array.isArray(item.columns) || !item.columns.length
|
|
25
|
+
|| item.columns.some((column) => { return typeof column?.name !== 'string' || typeof column.type !== 'string'
|
|
26
|
+
|| typeof column.nullable !== 'boolean'; }); })) { fail(); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Sorts opaque table rows and hashes the content independently of the export timestamp. */
|
|
30
|
+
export function tableSnapshotFormat({ tables: names, format, metadata = () => { return {}; } }) {
|
|
31
|
+
const sortedNames = canonicalJSON([...names].sort());
|
|
32
|
+
function seal({ schema, tables, createdAt = new Date().toISOString() }) {
|
|
33
|
+
tableSet(tables, names, sortedNames);
|
|
34
|
+
schemaValid(schema, sortedNames);
|
|
35
|
+
if (!Number.isFinite(Date.parse(createdAt))) { fail(); }
|
|
36
|
+
const sorted = Object.fromEntries(names.map((name) => {
|
|
37
|
+
return [name, [...tables[name]].sort(compareRows)];
|
|
38
|
+
}));
|
|
39
|
+
const content = { ...metadata(sorted), format, schemaHash: jsonDigest(schema), tables: sorted };
|
|
40
|
+
return { ...content, schema, createdAt, hash: jsonDigest(content) };
|
|
41
|
+
}
|
|
42
|
+
function validate(value, { maxBytes = tableSnapshotLimit } = {}) {
|
|
43
|
+
if (!value || Buffer.byteLength(JSON.stringify(value)) > maxBytes) { fail(); }
|
|
44
|
+
const expected = seal(value);
|
|
45
|
+
const fields = Object.keys(expected).filter((key) => { return !['schema', 'createdAt', 'tables'].includes(key); });
|
|
46
|
+
if (fields.some((key) => { return canonicalJSON(value[key]) !== canonicalJSON(expected[key]); })) { fail(); }
|
|
47
|
+
return expected;
|
|
48
|
+
}
|
|
49
|
+
return { seal, validate };
|
|
50
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import kubeServiceAccount from '../management/kubeServiceAccount.js';
|
|
2
|
+
import { tlsMaterialLimit, validateTLSMaterial } from './tlsMaterial.js';
|
|
3
|
+
|
|
4
|
+
function targetPath({namespace,name}) {
|
|
5
|
+
if (![namespace,name].every(value => { return typeof value === 'string' && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(value); })) {
|
|
6
|
+
throw new Error('TLS Secret target is invalid');
|
|
7
|
+
}
|
|
8
|
+
return `/api/v1/namespaces/${namespace}/secrets/${name}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function kubernetesTLSAPI(environment) {
|
|
12
|
+
const host = environment.KUBERNETES_SERVICE_HOST;
|
|
13
|
+
const port = environment.KUBERNETES_SERVICE_PORT_HTTPS || '443';
|
|
14
|
+
if (!host) { throw new Error('TLS Secret API address is missing'); }
|
|
15
|
+
const address = `https://${host.includes(':') ? `[${host}]` : host}:${port}`;
|
|
16
|
+
const request = kubeServiceAccount(address, { limit: tlsMaterialLimit, timeoutMs: 10000 });
|
|
17
|
+
async function exchange(path, method, body) {
|
|
18
|
+
try {
|
|
19
|
+
const result = await request(method, path, body);
|
|
20
|
+
if (result.status !== 200) { throw new Error('Refused'); }
|
|
21
|
+
return JSON.parse(result.body);
|
|
22
|
+
} catch { throw new Error('TLS Secret API request failed'); }
|
|
23
|
+
}
|
|
24
|
+
return {get:target => { return exchange(targetPath(target),'GET'); },update:(target,body) => { return exchange(targetPath(target),'PUT',body); }};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Update an already-existing named Secret only; RBAC grants no create or namespace discovery. */
|
|
28
|
+
export async function mirrorTLSSecret(payload, { target, hosts, api, roots, format }) {
|
|
29
|
+
const data = validateTLSMaterial(payload, { hosts, roots, format });
|
|
30
|
+
targetPath(target);
|
|
31
|
+
const secret = await api.get(target);
|
|
32
|
+
if (secret.metadata?.name !== target.name || secret.metadata?.namespace !== target.namespace
|
|
33
|
+
|| !secret.metadata?.resourceVersion || secret.type !== 'kubernetes.io/tls') { throw new Error('TLS Secret target does not match'); }
|
|
34
|
+
if (secret.data?.['tls.crt'] === data['tls.crt'] && secret.data?.['tls.key'] === data['tls.key']) { return false; }
|
|
35
|
+
await api.update(target,{...secret,data:{...secret.data,...data}});
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { createServer, request } from 'node:https';
|
|
3
|
+
|
|
4
|
+
const defaultLimit = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
export function readMutualTLS({ key, cert, ca }) {
|
|
7
|
+
try {
|
|
8
|
+
return { key: readFileSync(key), cert: readFileSync(cert), ca: readFileSync(ca), minVersion: 'TLSv1.2' };
|
|
9
|
+
} catch { throw new Error('Mutual TLS files are required'); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function respond(response, status, body) {
|
|
13
|
+
response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(body);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function respondJSON(response, { read, maxBytes = defaultLimit, unavailable }) {
|
|
17
|
+
try {
|
|
18
|
+
const result = await read();
|
|
19
|
+
if (result === undefined) {
|
|
20
|
+
respond(response, 404, '{"error":"Not found"}');
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const body = JSON.stringify(result);
|
|
24
|
+
if (Buffer.byteLength(body) > maxBytes) { throw new Error('JSON body limit exceeded'); }
|
|
25
|
+
respond(response, 200, body);
|
|
26
|
+
} catch { respond(response, 503, JSON.stringify({ error: unavailable || 'Resource unavailable' })); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function serveMutualTLS({ tls, routes }) {
|
|
30
|
+
const server = createServer({ ...tls, requestCert: true, rejectUnauthorized: true, minVersion: 'TLSv1.2' }, (incoming, response) => {
|
|
31
|
+
if (!incoming.socket.authorized) { respond(response, 403, '{"error":"Client certificate required"}'); }
|
|
32
|
+
else if (incoming.method !== 'GET') { respond(response, 405, '{"error":"Method not allowed"}'); }
|
|
33
|
+
else if (Object.hasOwn(routes, incoming.url)) { void respondJSON(response, routes[incoming.url]); }
|
|
34
|
+
else { respond(response, 404, '{"error":"Not found"}'); }
|
|
35
|
+
});
|
|
36
|
+
server.requestTimeout = 30000;
|
|
37
|
+
server.headersTimeout = 10000;
|
|
38
|
+
server.maxConnections = 8;
|
|
39
|
+
return server;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function collect(response, resolve, reject, maxBytes, decode) {
|
|
43
|
+
const chunks = [];
|
|
44
|
+
let size = 0;
|
|
45
|
+
response.on('data', (chunk) => {
|
|
46
|
+
size += chunk.length;
|
|
47
|
+
if (size > maxBytes) { response.destroy(new Error('JSON body limit exceeded')); }
|
|
48
|
+
else { chunks.push(chunk); }
|
|
49
|
+
});
|
|
50
|
+
response.on('error', () => { reject(new Error('HTTPS transport failed')); });
|
|
51
|
+
response.on('end', () => {
|
|
52
|
+
try { resolve(decode(JSON.parse(Buffer.concat(chunks).toString('utf8')))); }
|
|
53
|
+
catch { reject(new Error('HTTPS JSON response is invalid')); }
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function fetchMutualJSON({ url, tls, maxBytes = defaultLimit, path, decode = (value) => { return value; }, optional }) {
|
|
58
|
+
const address = new URL(url);
|
|
59
|
+
if (address.protocol !== 'https:' || address.username || address.password) {
|
|
60
|
+
throw new Error('JSON transport requires HTTPS without credentials');
|
|
61
|
+
}
|
|
62
|
+
if (address.pathname !== path || address.search || address.hash) {
|
|
63
|
+
throw new Error(`JSON transport requires the ${path} endpoint`);
|
|
64
|
+
}
|
|
65
|
+
return await new Promise((resolve, reject) => {
|
|
66
|
+
const connection = request(address, {
|
|
67
|
+
...tls, method: 'GET', rejectUnauthorized: true, minVersion: 'TLSv1.2', timeout: 20000, agent: false
|
|
68
|
+
}, (response) => {
|
|
69
|
+
if (optional && response.statusCode === 404) { response.resume(); resolve(null); return; }
|
|
70
|
+
if (response.statusCode !== 200 || !response.headers['content-type']?.startsWith('application/json')) {
|
|
71
|
+
response.resume(); reject(new Error('HTTPS endpoint refused the request')); return;
|
|
72
|
+
}
|
|
73
|
+
collect(response, resolve, reject, maxBytes, decode);
|
|
74
|
+
});
|
|
75
|
+
connection.on('timeout', () => { connection.destroy(new Error('HTTPS request timed out')); });
|
|
76
|
+
connection.on('error', () => { reject(new Error('HTTPS transport failed')); });
|
|
77
|
+
connection.end();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import {createPrivateKey, createPublicKey, X509Certificate} from 'node:crypto';
|
|
2
|
+
import {rootCertificates} from 'node:tls';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { jsonDigest } from '../replication/canonicalJSON.js';
|
|
5
|
+
|
|
6
|
+
export const tlsMaterialLimit = 1024 * 1024;
|
|
7
|
+
const defaultFormat = 'tls-material-v1';
|
|
8
|
+
|
|
9
|
+
function invalid() { throw new Error('Public TLS renewal is invalid'); }
|
|
10
|
+
|
|
11
|
+
export function sealTLSMaterial(cert, key, { format = defaultFormat } = {}) {
|
|
12
|
+
const content = {cert:Buffer.from(cert).toString('base64'),key:Buffer.from(key).toString('base64')};
|
|
13
|
+
return {format, ...content, hash: jsonDigest(content)};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function chain(cert) {
|
|
17
|
+
const blocks = cert.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/gu);
|
|
18
|
+
if (!blocks?.length || blocks.length > 8) { invalid(); }
|
|
19
|
+
return blocks.map(block => { return new X509Certificate(block); });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function trusted(certificates, roots, now) {
|
|
23
|
+
if (certificates.some(cert => { return now < Date.parse(cert.validFrom) || now >= Date.parse(cert.validTo); })) { invalid(); }
|
|
24
|
+
const linked = certificates.every((cert,index) => {
|
|
25
|
+
return index === certificates.length - 1 || certificates[index + 1].ca
|
|
26
|
+
&& cert.checkIssued(certificates[index + 1]) && cert.verify(certificates[index + 1].publicKey);
|
|
27
|
+
});
|
|
28
|
+
const last = certificates[certificates.length - 1];
|
|
29
|
+
if (!linked || !roots.some(pem => {
|
|
30
|
+
const root = new X509Certificate(pem);
|
|
31
|
+
return now >= Date.parse(root.validFrom) && now < Date.parse(root.validTo)
|
|
32
|
+
&& (last.raw.equals(root.raw) || last.checkIssued(root) && last.verify(root.publicKey));
|
|
33
|
+
})) { invalid(); }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function validateTLSMaterial(payload, { hosts, roots = rootCertificates, now = Date.now(), format = defaultFormat }) {
|
|
37
|
+
try {
|
|
38
|
+
if (!payload || payload.format !== format || typeof payload.cert !== 'string'
|
|
39
|
+
|| typeof payload.key !== 'string' || payload.hash !== jsonDigest({cert:payload.cert,key:payload.key})
|
|
40
|
+
|| !Array.isArray(hosts) || !hosts.length || Buffer.byteLength(JSON.stringify(payload)) > tlsMaterialLimit) { invalid(); }
|
|
41
|
+
const certificates = chain(Buffer.from(payload.cert,'base64').toString('utf8'));
|
|
42
|
+
const [leaf] = certificates;
|
|
43
|
+
if (leaf.ca || hosts.some(host => { return !leaf.checkHost(host); })
|
|
44
|
+
|| leaf.keyUsage?.length && !leaf.keyUsage.includes('1.3.6.1.5.5.7.3.1') && !leaf.keyUsage.includes('2.5.29.37.0')) { invalid(); }
|
|
45
|
+
const publicKey = createPublicKey(createPrivateKey(Buffer.from(payload.key,'base64'))).export({type:'spki',format:'der'});
|
|
46
|
+
if (!leaf.publicKey.export({type:'spki',format:'der'}).equals(publicKey)) { invalid(); }
|
|
47
|
+
trusted(certificates,roots,now);
|
|
48
|
+
return {'tls.crt':payload.cert,'tls.key':payload.key};
|
|
49
|
+
} catch { invalid(); }
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Read material per request so a rotating secret is served without restarting the origin. */
|
|
54
|
+
export function readTLSMaterial({ cert, key } = {}, options = {}) {
|
|
55
|
+
if (cert && key) { return sealTLSMaterial(readFileSync(cert), readFileSync(key), options); }
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
package scada.processing.infra.state
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.circe.{Decoder, Encoder}
|
|
6
|
+
import io.circe.parser.decode
|
|
7
|
+
import io.circe.syntax.*
|
|
4
8
|
import java.nio.ByteBuffer
|
|
5
9
|
import java.nio.channels.FileChannel
|
|
6
10
|
import java.nio.file.{Files, Path, StandardCopyOption, StandardOpenOption}
|
|
@@ -10,6 +14,9 @@ import java.nio.charset.StandardCharsets.UTF_8
|
|
|
10
14
|
final class AtomicStateFile(path: Path):
|
|
11
15
|
def read: IO[Option[String]] = IO.blocking:
|
|
12
16
|
if Files.exists(path) then Some(Files.readString(path)) else None
|
|
17
|
+
def readJson[A: Decoder]: IO[Option[A]] = read.flatMap(_.traverse(json => IO.fromEither(decode[A](json))))
|
|
18
|
+
def writeJson[A: Encoder](value: A): IO[Unit] = write(value.asJson.noSpaces)
|
|
19
|
+
|
|
13
20
|
def write(json: String): IO[Unit] = IO.blocking:
|
|
14
21
|
Files.createDirectories(path.getParent)
|
|
15
22
|
val temporary = path.resolveSibling(path.getFileName.toString + ".tmp")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
package scada.processing.infra.state
|
|
2
|
+
|
|
3
|
+
import cats.effect.{IO, Resource}
|
|
4
|
+
import cats.syntax.all.*
|
|
5
|
+
import io.circe.{Decoder, Encoder}
|
|
6
|
+
import java.nio.channels.FileChannel
|
|
7
|
+
import java.nio.file.{Files, Path, StandardOpenOption}
|
|
8
|
+
|
|
9
|
+
/** Owns a process lock while reading or saving an atomically replaced JSON checkpoint. */
|
|
10
|
+
final class StateJournal[A: Encoder: Decoder] private (file: AtomicStateFile, initial: A):
|
|
11
|
+
def load: IO[A] = file.readJson[A].map(_.getOrElse(initial))
|
|
12
|
+
def save(checkpoint: A): IO[Unit] = file.writeJson(checkpoint)
|
|
13
|
+
|
|
14
|
+
object StateJournal:
|
|
15
|
+
def open[A: Encoder: Decoder](file: String, initial: A): Resource[IO, StateJournal[A]] =
|
|
16
|
+
val path = Path.of(file).toAbsolutePath
|
|
17
|
+
val lockPath = path.resolveSibling(path.getFileName.toString + ".lock")
|
|
18
|
+
Resource.eval(IO.blocking(Files.createDirectories(path.getParent))) *>
|
|
19
|
+
Resource.fromAutoCloseable(IO.blocking(FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE))).flatMap: channel =>
|
|
20
|
+
Resource.make(IO.blocking(Option(channel.tryLock()).getOrElse(throw IllegalStateException(s"Checkpoint already owned: $file"))))(
|
|
21
|
+
lock => IO.blocking(lock.release())
|
|
22
|
+
).as(new StateJournal(AtomicStateFile(path), initial))
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
package scada.processing.runtime
|
|
2
2
|
|
|
3
3
|
import cats.effect.IO
|
|
4
|
-
import io.circe.Json
|
|
4
|
+
import io.circe.{Json, Printer}
|
|
5
5
|
import io.circe.parser.parse
|
|
6
6
|
import java.net.URI
|
|
7
7
|
import java.net.http.{HttpClient,HttpRequest,HttpResponse}
|
|
8
8
|
import java.time.Duration
|
|
9
|
+
import java.nio.charset.StandardCharsets.UTF_8
|
|
10
|
+
import java.security.MessageDigest
|
|
11
|
+
import java.util.HexFormat
|
|
9
12
|
import scada.processing.infra.config.{AppConfig, CheckpointApiConfig}
|
|
10
13
|
import scala.concurrent.duration.*
|
|
11
14
|
|
|
@@ -54,3 +57,9 @@ final class HistoryClient(config: CheckpointApiConfig):
|
|
|
54
57
|
attempt(2)
|
|
55
58
|
|
|
56
59
|
def retry[A](action: IO[A]): IO[A] = action.handleErrorWith(_=>IO.sleep(2.seconds) *> retry(action))
|
|
60
|
+
|
|
61
|
+
object HistoryClient:
|
|
62
|
+
/** Stable fingerprint for classifier configuration and claimed work. */
|
|
63
|
+
def fingerprint(value: Json): String =
|
|
64
|
+
val bytes = Printer.noSpaces.copy(sortKeys = true).print(value).getBytes(UTF_8)
|
|
65
|
+
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))
|