@waswrongassembled/pii-shield 0.1.1 → 0.3.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/CHANGELOG.md +36 -1
- package/README.md +135 -21
- package/dist/cli.js +37 -5
- package/dist/create-pii-shield.d.ts +91 -0
- package/dist/create-pii-shield.js +124 -0
- package/dist/entity-extractor.d.ts +7 -0
- package/dist/entity-extractor.js +6 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/internal/background.d.ts +27 -0
- package/dist/internal/background.js +47 -0
- package/dist/learning/custom-entity-type.d.ts +14 -4
- package/dist/learning/custom-entity-type.js +23 -5
- package/dist/learning/entity-learner.d.ts +33 -2
- package/dist/learning/entity-learner.js +48 -5
- package/dist/learning/store.d.ts +26 -5
- package/dist/learning/store.js +4 -2
- package/dist/pii-masker.js +2 -1
- package/dist/pii-shield.js +2 -1
- package/dist/postgres/index.d.ts +103 -0
- package/dist/postgres/index.js +204 -0
- package/dist/redaction.d.ts +16 -2
- package/dist/redaction.js +22 -10
- package/dist/server/config.d.ts +16 -7
- package/dist/server/config.js +78 -126
- package/dist/server/connections.d.ts +34 -0
- package/dist/server/connections.js +99 -0
- package/dist/server/doctor.d.ts +28 -0
- package/dist/server/doctor.js +438 -0
- package/dist/server/env.d.ts +62 -0
- package/dist/server/env.js +197 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/dist/testing/conformance.d.ts +64 -0
- package/dist/testing/conformance.js +348 -0
- package/dist/testing/index.d.ts +6 -0
- package/dist/testing/index.js +6 -0
- package/dist/vault/encrypted-vault.d.ts +39 -2
- package/dist/vault/encrypted-vault.js +96 -13
- package/dist/vault/memory-vault-storage.d.ts +8 -1
- package/dist/vault/memory-vault-storage.js +20 -8
- package/dist/vault/vault.d.ts +18 -2
- package/dist/vault-redis/index.d.ts +14 -0
- package/dist/vault-redis/index.js +8 -0
- package/docs/openapi.yaml +8 -2
- package/package.json +18 -3
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { ConfigError, readDatabaseUrl, readRedisUrl } from './env.js';
|
|
2
|
+
export function connections(get, options) {
|
|
3
|
+
let redis;
|
|
4
|
+
let pool;
|
|
5
|
+
// Both URLs can hold a password: error messages never quote them.
|
|
6
|
+
const secretUrls = [
|
|
7
|
+
[get('PII_SERVICE_DATABASE_URL'), 'PII_SERVICE_DATABASE_URL'],
|
|
8
|
+
[get('PII_SERVICE_REDIS_URL') ?? get('PII_DEMO_REDIS_URL'), 'PII_SERVICE_REDIS_URL'],
|
|
9
|
+
];
|
|
10
|
+
return {
|
|
11
|
+
redis: async () => {
|
|
12
|
+
const url = readRedisUrl(get);
|
|
13
|
+
if (redis === undefined) {
|
|
14
|
+
let Redis;
|
|
15
|
+
try {
|
|
16
|
+
({ Redis } = (await import('ioredis')));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new ConfigError('The redis store needs the package "ioredis" (npm install ioredis).');
|
|
20
|
+
}
|
|
21
|
+
if (options.failFast === true) {
|
|
22
|
+
const client = new Redis(url, {
|
|
23
|
+
lazyConnect: true,
|
|
24
|
+
maxRetriesPerRequest: 0,
|
|
25
|
+
connectTimeout: 5000,
|
|
26
|
+
retryStrategy: () => null,
|
|
27
|
+
});
|
|
28
|
+
// connect() rejects with the error; without a listener ioredis also prints it.
|
|
29
|
+
let cause;
|
|
30
|
+
client.on('error', (e) => {
|
|
31
|
+
cause ??= e;
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
await client.connect();
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
client.disconnect();
|
|
38
|
+
// connect() only says "Connection is closed."; the error event has the reason (ECONNREFUSED).
|
|
39
|
+
throw cause ?? e;
|
|
40
|
+
}
|
|
41
|
+
redis = client;
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
redis = new Redis(url);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return redis;
|
|
48
|
+
},
|
|
49
|
+
postgres: async () => {
|
|
50
|
+
const url = readDatabaseUrl(get);
|
|
51
|
+
if (pool === undefined) {
|
|
52
|
+
let Pool;
|
|
53
|
+
try {
|
|
54
|
+
const pg = (await import('pg'));
|
|
55
|
+
Pool = pg.Pool ?? pg.default?.Pool;
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// reported below
|
|
59
|
+
}
|
|
60
|
+
if (Pool === undefined) {
|
|
61
|
+
throw new ConfigError('The postgres store needs the package "pg" (npm install pg).');
|
|
62
|
+
}
|
|
63
|
+
pool = new Pool({
|
|
64
|
+
connectionString: url,
|
|
65
|
+
...(options.failFast === true ? { connectionTimeoutMillis: 5000 } : {}),
|
|
66
|
+
});
|
|
67
|
+
pool.on('error', options.onPoolError);
|
|
68
|
+
}
|
|
69
|
+
const connected = pool;
|
|
70
|
+
return (text, params) => connected.query(text, params);
|
|
71
|
+
},
|
|
72
|
+
safeMessage: (e) => {
|
|
73
|
+
let message = e instanceof Error ? e.message : String(e);
|
|
74
|
+
for (const [url, name] of secretUrls) {
|
|
75
|
+
if (url === undefined) {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
message = message.split(url).join(`<${name}>`);
|
|
79
|
+
const password = URL.canParse(url) ? decodeURIComponent(new URL(url).password) : '';
|
|
80
|
+
if (password !== '') {
|
|
81
|
+
message = message.split(password).join('***');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return message;
|
|
85
|
+
},
|
|
86
|
+
close: async () => {
|
|
87
|
+
await Promise.all([redis?.quit(), pool?.end()]);
|
|
88
|
+
},
|
|
89
|
+
closeQuietly: async () => {
|
|
90
|
+
if (options.failFast === true) {
|
|
91
|
+
redis?.disconnect();
|
|
92
|
+
}
|
|
93
|
+
await Promise.all([
|
|
94
|
+
options.failFast === true ? undefined : redis?.quit().catch(() => undefined),
|
|
95
|
+
pool?.end().catch(() => undefined),
|
|
96
|
+
]);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type Env } from './env.js';
|
|
2
|
+
/** `error`: the service would not start or not work; `warning`: it works, but should be changed. */
|
|
3
|
+
export type FindingSeverity = 'error' | 'warning' | 'info' | 'ok';
|
|
4
|
+
export interface ConfigFinding {
|
|
5
|
+
readonly severity: FindingSeverity;
|
|
6
|
+
/** What was checked, a stable id such as `vault-key`, `token` or `database-tls`. */
|
|
7
|
+
readonly check: string;
|
|
8
|
+
/** For the operator; names variables, never their values. */
|
|
9
|
+
readonly message: string;
|
|
10
|
+
}
|
|
11
|
+
export interface CheckServiceConfigOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Also connect to Redis and PostgreSQL (when configured): checks that they answer, that the tables
|
|
14
|
+
* exist and are readable, and the database role's rights. Reads only, never writes. Default false.
|
|
15
|
+
*/
|
|
16
|
+
connect?: boolean;
|
|
17
|
+
/** The listen address if it is given on the command line (`--host`), else PII_SERVICE_HOST. */
|
|
18
|
+
host?: string | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Checks the service configuration in `env` (the variables of docs/server.md) and returns findings,
|
|
22
|
+
* errors first in each area. Nothing is printed; secrets are never part of a finding. Without
|
|
23
|
+
* `connect` it is static (it only looks at files for the learned types).
|
|
24
|
+
*/
|
|
25
|
+
export declare function checkServiceConfig(env?: Env, options?: CheckServiceConfigOptions): Promise<ConfigFinding[]>;
|
|
26
|
+
/** The findings as text, one line each, and a summary. */
|
|
27
|
+
export declare function formatFindings(findings: readonly ConfigFinding[]): string;
|
|
28
|
+
export declare function countFindings(findings: readonly ConfigFinding[]): Record<FindingSeverity, number>;
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pii-shield doctor`: checks the service configuration from the environment with the rules of
|
|
3
|
+
* serviceFromEnv() (src/server/env.ts) plus security recommendations. Findings name variables, never
|
|
4
|
+
* their values: no token, key, URL, password or provider key appears in a message.
|
|
5
|
+
*/
|
|
6
|
+
import { constants } from 'node:fs';
|
|
7
|
+
import { access, stat } from 'node:fs/promises';
|
|
8
|
+
import { dirname } from 'node:path';
|
|
9
|
+
import { KeyValueCustomEntityStore } from '../learning/store.js';
|
|
10
|
+
import { ModelLocation } from '../model/model-detector.js';
|
|
11
|
+
import { splitList } from '../service/local-peer.js';
|
|
12
|
+
import { connections } from './connections.js';
|
|
13
|
+
import { assertVaultKeyFor, ConfigError, envGetter, readDatabaseUrl, readKeepExamples, readLearnedStore, readListen, readModel, readPreviousVaultKeys, readPurgeInterval, readRedisUrl, readVaultKey, readVaultStore, readVaultTtl, } from './env.js';
|
|
14
|
+
/** The longest vault TTL without a warning: one hour. */
|
|
15
|
+
const MAX_RECOMMENDED_TTL = 3600;
|
|
16
|
+
const MIN_TOKEN_LENGTH = 32;
|
|
17
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
|
|
18
|
+
/**
|
|
19
|
+
* Checks the service configuration in `env` (the variables of docs/server.md) and returns findings,
|
|
20
|
+
* errors first in each area. Nothing is printed; secrets are never part of a finding. Without
|
|
21
|
+
* `connect` it is static (it only looks at files for the learned types).
|
|
22
|
+
*/
|
|
23
|
+
export async function checkServiceConfig(env = process.env, options = {}) {
|
|
24
|
+
const get = envGetter(env);
|
|
25
|
+
const findings = [];
|
|
26
|
+
const add = (severity, check, message) => {
|
|
27
|
+
findings.push(Object.freeze({ severity, check, message }));
|
|
28
|
+
};
|
|
29
|
+
/** Runs one of serviceFromEnv()'s readers; its ConfigError becomes an error finding. */
|
|
30
|
+
const read = (check, reader) => {
|
|
31
|
+
try {
|
|
32
|
+
return reader();
|
|
33
|
+
}
|
|
34
|
+
catch (e) {
|
|
35
|
+
if (e instanceof ConfigError) {
|
|
36
|
+
add('error', check, e.message);
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
throw e;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
// Vault
|
|
43
|
+
const vaultStore = read('vault-store', () => readVaultStore(get));
|
|
44
|
+
const key = read('vault-key', () => readVaultKey(get));
|
|
45
|
+
const previousKeys = read('vault-previous-keys', () => readPreviousVaultKeys(get, env)) ?? [];
|
|
46
|
+
try {
|
|
47
|
+
if (key !== undefined) {
|
|
48
|
+
add('ok', 'vault-key', 'PII_SERVICE_VAULT_KEY is set and valid.');
|
|
49
|
+
}
|
|
50
|
+
else if (get('PII_SERVICE_VAULT_KEY') === undefined && vaultStore === 'memory') {
|
|
51
|
+
add('info', 'vault-key', 'PII_SERVICE_VAULT_KEY is not set: a random key per process (fine for the memory vault).');
|
|
52
|
+
}
|
|
53
|
+
else if (get('PII_SERVICE_VAULT_KEY') === undefined && vaultStore !== undefined) {
|
|
54
|
+
read('vault-key', () => {
|
|
55
|
+
assertVaultKeyFor(vaultStore, false);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (previousKeys.length > 0) {
|
|
59
|
+
if (key !== undefined && previousKeys.some((previous) => Buffer.from(previous).equals(Buffer.from(key)))) {
|
|
60
|
+
add('warning', 'vault-previous-keys', 'PII_SERVICE_VAULT_PREVIOUS_KEYS contains the current key.');
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
add('info', 'vault-previous-keys', `PII_SERVICE_VAULT_PREVIOUS_KEYS: ${String(previousKeys.length)} valid key(s). Remove them once the longest vault TTL since the rotation has passed.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
key?.fill(0);
|
|
69
|
+
for (const previous of previousKeys) {
|
|
70
|
+
previous.fill(0);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (vaultStore === 'memory') {
|
|
74
|
+
add('info', 'vault-store', 'Vault in memory: mappings are lost on restart and not shared between instances.');
|
|
75
|
+
}
|
|
76
|
+
else if (vaultStore !== undefined) {
|
|
77
|
+
add('ok', 'vault-store', `Vault in ${vaultStore}.`);
|
|
78
|
+
}
|
|
79
|
+
const ttl = read('vault-ttl', () => readVaultTtl(get));
|
|
80
|
+
if (ttl !== undefined) {
|
|
81
|
+
if (ttl > MAX_RECOMMENDED_TTL) {
|
|
82
|
+
add('warning', 'vault-ttl', 'PII_SERVICE_VAULT_TTL is above one hour: keep mappings only as long as a request needs them (storage limitation, Art. 5(1)(e) GDPR).');
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
add('ok', 'vault-ttl', `Vault TTL ${String(ttl)} s.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const purgeInterval = vaultStore === 'postgres' ? read('vault-purge', () => readPurgeInterval(get)) : undefined;
|
|
89
|
+
if (purgeInterval === 0) {
|
|
90
|
+
add('warning', 'vault-purge', 'PII_SERVICE_VAULT_PURGE_INTERVAL=0: expired vault rows are not deleted by the service; make sure a job (e.g. pg_cron) deletes them.');
|
|
91
|
+
}
|
|
92
|
+
else if (purgeInterval !== undefined) {
|
|
93
|
+
add('ok', 'vault-purge', `Expired vault rows are deleted every ${String(purgeInterval)} s.`);
|
|
94
|
+
}
|
|
95
|
+
// Access
|
|
96
|
+
const token = get('PII_SERVICE_TOKEN');
|
|
97
|
+
const serviceOnly = get('PII_SERVICE_ONLY') === '1';
|
|
98
|
+
if (token === undefined) {
|
|
99
|
+
if (serviceOnly) {
|
|
100
|
+
add('error', 'token', 'PII_SERVICE_ONLY=1 without PII_SERVICE_TOKEN: every request is answered with 503.');
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
add('warning', 'token', 'PII_SERVICE_TOKEN is not set: only local peers are answered (127.0.0.1, ::1, PII_LOCAL_PEERS). Set a token for anything reachable from the network.');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
else if (token.length < MIN_TOKEN_LENGTH) {
|
|
107
|
+
add('warning', 'token', `PII_SERVICE_TOKEN is shorter than ${String(MIN_TOKEN_LENGTH)} characters: use a long random token (openssl rand -hex 24).`);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
add('ok', 'token', 'PII_SERVICE_TOKEN is set.');
|
|
111
|
+
}
|
|
112
|
+
const listen = read('listen', () => readListen(get));
|
|
113
|
+
if (listen !== undefined) {
|
|
114
|
+
const host = options.host ?? listen.host;
|
|
115
|
+
const loopback = isLoopback(host);
|
|
116
|
+
if (loopback) {
|
|
117
|
+
add('ok', 'listen', 'The service listens on a loopback address.');
|
|
118
|
+
}
|
|
119
|
+
else if (token === undefined) {
|
|
120
|
+
add('warning', 'listen', `The service listens on ${host === '0.0.0.0' || host === '::' || host === '[::]' ? 'all interfaces' : 'a non-loopback address'} without PII_SERVICE_TOKEN: set a token (and PII_SERVICE_ONLY=1).`);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
add('info', 'listen', 'The service listens on a non-loopback address and speaks plain HTTP: put a reverse proxy with TLS in front, set PII_SERVICE_ONLY=1 and PII_SERVICE_ALLOWED_HOSTS.');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (token === undefined && splitList(get('PII_LOCAL_PEERS')).length > 0) {
|
|
127
|
+
add('info', 'local-peers', 'PII_LOCAL_PEERS: these addresses are answered without a token.');
|
|
128
|
+
}
|
|
129
|
+
// Learned types
|
|
130
|
+
const learned = read('learned-store', () => readLearnedStore(get));
|
|
131
|
+
if (learned?.kind === 'memory') {
|
|
132
|
+
add('info', 'learned-store', 'Learned types in memory: they are lost on restart.');
|
|
133
|
+
}
|
|
134
|
+
else if (learned?.kind === 'file') {
|
|
135
|
+
add(...(await checkLearnedFile(learned.file ?? '')));
|
|
136
|
+
}
|
|
137
|
+
else if (learned !== undefined) {
|
|
138
|
+
add('ok', 'learned-store', `Learned types in ${learned.kind}.`);
|
|
139
|
+
}
|
|
140
|
+
const keepExamples = read('learned-examples', () => readKeepExamples(get));
|
|
141
|
+
if (keepExamples === true) {
|
|
142
|
+
add(learned === undefined || learned.kind === 'memory' ? 'info' : 'warning', 'learned-examples', 'Learned types keep their examples and counter-examples in plain text (may be personal data). PII_SERVICE_LEARNED_KEEP_EXAMPLES=false stores name, description and pattern only (model-only types are then refused).');
|
|
143
|
+
}
|
|
144
|
+
else if (keepExamples === false) {
|
|
145
|
+
add('ok', 'learned-examples', 'Learned types are stored without examples; model-only types (no pattern) are refused.');
|
|
146
|
+
}
|
|
147
|
+
// Connections
|
|
148
|
+
const usesPostgres = vaultStore === 'postgres' || learned?.kind === 'postgres';
|
|
149
|
+
const usesRedis = vaultStore === 'redis' || learned?.kind === 'redis';
|
|
150
|
+
let databaseUrl;
|
|
151
|
+
if (usesPostgres) {
|
|
152
|
+
databaseUrl = read('database-url', () => readDatabaseUrl(get));
|
|
153
|
+
if (databaseUrl !== undefined) {
|
|
154
|
+
add(...databaseTls(new URL(databaseUrl), get('PGSSLMODE')));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
else if (get('PII_SERVICE_DATABASE_URL') !== undefined) {
|
|
158
|
+
add('info', 'database-url', 'PII_SERVICE_DATABASE_URL is set, but no store uses postgres.');
|
|
159
|
+
}
|
|
160
|
+
let redisUrl;
|
|
161
|
+
if (usesRedis) {
|
|
162
|
+
redisUrl = read('redis-url', () => readRedisUrl(get));
|
|
163
|
+
if (redisUrl !== undefined) {
|
|
164
|
+
add(...redisTls(redisUrl));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// Model
|
|
168
|
+
const model = read('model', () => readModel(get));
|
|
169
|
+
if (model === undefined) {
|
|
170
|
+
if (get('PII_SERVICE_MODEL_PROVIDER') === undefined) {
|
|
171
|
+
add('info', 'model', 'No model provider: detection uses patterns and checksums only.');
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
add(...modelFinding(model, get('PII_SERVICE_MODEL_URL') ?? get('PII_DEMO_OLLAMA_URL')));
|
|
176
|
+
}
|
|
177
|
+
if (options.connect === true) {
|
|
178
|
+
const reachable = {
|
|
179
|
+
postgres: usesPostgres && databaseUrl !== undefined,
|
|
180
|
+
redis: usesRedis && redisUrl !== undefined,
|
|
181
|
+
};
|
|
182
|
+
if (reachable.postgres || reachable.redis) {
|
|
183
|
+
findings.push(...(await connectChecks(get, {
|
|
184
|
+
...reachable,
|
|
185
|
+
vaultStore,
|
|
186
|
+
learnedStore: learned?.kind,
|
|
187
|
+
keepExamples,
|
|
188
|
+
purgeInterval,
|
|
189
|
+
localDatabase: databaseUrl !== undefined && isLocalDatabase(new URL(databaseUrl)),
|
|
190
|
+
})));
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
add('info', 'connect', 'Nothing to connect to: no store uses Redis or PostgreSQL.');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return findings;
|
|
197
|
+
}
|
|
198
|
+
async function checkLearnedFile(file) {
|
|
199
|
+
try {
|
|
200
|
+
if ((await stat(file)).isDirectory()) {
|
|
201
|
+
return ['error', 'learned-store', 'PII_SERVICE_LEARNED_TYPES is a directory, not a file.'];
|
|
202
|
+
}
|
|
203
|
+
await access(file, constants.R_OK | constants.W_OK);
|
|
204
|
+
return ['ok', 'learned-store', 'Learned types in a JSON file (PII_SERVICE_LEARNED_TYPES), readable and writable.'];
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
if (e.code !== 'ENOENT') {
|
|
208
|
+
return ['error', 'learned-store', 'PII_SERVICE_LEARNED_TYPES cannot be read and written by this user.'];
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
await access(dirname(file), constants.W_OK);
|
|
213
|
+
return ['ok', 'learned-store', 'PII_SERVICE_LEARNED_TYPES does not exist yet; it is created with the first type.'];
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
return [
|
|
217
|
+
'error',
|
|
218
|
+
'learned-store',
|
|
219
|
+
'PII_SERVICE_LEARNED_TYPES does not exist and its directory is missing or not writable.',
|
|
220
|
+
];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function isLoopback(host) {
|
|
224
|
+
return LOOPBACK_HOSTS.has(host) || host.startsWith('127.');
|
|
225
|
+
}
|
|
226
|
+
function isLocalDatabase(url) {
|
|
227
|
+
const socket = url.searchParams.get('host');
|
|
228
|
+
return socket?.startsWith('/') === true || url.hostname === '' || isLoopback(url.hostname);
|
|
229
|
+
}
|
|
230
|
+
/** sslmode of the URL (or PGSSLMODE); a remote database needs TLS that verifies the server. */
|
|
231
|
+
function databaseTls(url, envSslMode) {
|
|
232
|
+
if (isLocalDatabase(url)) {
|
|
233
|
+
return ['ok', 'database-tls', 'The database is on this machine; TLS is not required.'];
|
|
234
|
+
}
|
|
235
|
+
const sslMode = url.searchParams.get('sslmode') ?? envSslMode;
|
|
236
|
+
const ssl = url.searchParams.get('ssl');
|
|
237
|
+
if (sslMode === 'verify-full') {
|
|
238
|
+
return ['ok', 'database-tls', 'The database connection uses TLS with sslmode=verify-full.'];
|
|
239
|
+
}
|
|
240
|
+
if (sslMode === 'require' || sslMode === 'verify-ca' || sslMode === 'no-verify') {
|
|
241
|
+
return [
|
|
242
|
+
'warning',
|
|
243
|
+
'database-tls',
|
|
244
|
+
`sslmode=${sslMode} in PII_SERVICE_DATABASE_URL does not check the server's name (libpq semantics): use sslmode=verify-full.`,
|
|
245
|
+
];
|
|
246
|
+
}
|
|
247
|
+
if (sslMode === undefined && (ssl === 'true' || ssl === '1')) {
|
|
248
|
+
return [
|
|
249
|
+
'warning',
|
|
250
|
+
'database-tls',
|
|
251
|
+
'PII_SERVICE_DATABASE_URL enables TLS with ssl=true: prefer sslmode=verify-full.',
|
|
252
|
+
];
|
|
253
|
+
}
|
|
254
|
+
return [
|
|
255
|
+
'error',
|
|
256
|
+
'database-tls',
|
|
257
|
+
`The database is not on this machine and PII_SERVICE_DATABASE_URL ${sslMode === undefined ? 'has no sslmode' : `has sslmode=${['disable', 'allow', 'prefer'].includes(sslMode) ? sslMode : 'of an unknown value'}`}: TLS is not enforced. Add sslmode=verify-full (at least require).`,
|
|
258
|
+
];
|
|
259
|
+
}
|
|
260
|
+
function redisTls(url) {
|
|
261
|
+
if (!URL.canParse(url)) {
|
|
262
|
+
return ['warning', 'redis-tls', 'PII_SERVICE_REDIS_URL is not a URL (redis:// or rediss://).'];
|
|
263
|
+
}
|
|
264
|
+
const parsed = new URL(url);
|
|
265
|
+
if (parsed.protocol === 'rediss:') {
|
|
266
|
+
return ['ok', 'redis-tls', 'Redis is reached over TLS (rediss://).'];
|
|
267
|
+
}
|
|
268
|
+
if (isLoopback(parsed.hostname)) {
|
|
269
|
+
return ['ok', 'redis-tls', 'Redis is on this machine; TLS is not required.'];
|
|
270
|
+
}
|
|
271
|
+
return [
|
|
272
|
+
'warning',
|
|
273
|
+
'redis-tls',
|
|
274
|
+
'Redis is not on this machine and is reached without TLS: use a rediss:// URL (learned types are stored in plain text).',
|
|
275
|
+
];
|
|
276
|
+
}
|
|
277
|
+
function modelFinding(model, endpoint) {
|
|
278
|
+
if (model.location === ModelLocation.External) {
|
|
279
|
+
return [
|
|
280
|
+
'warning',
|
|
281
|
+
'model',
|
|
282
|
+
`${model.provider} is an external provider and PII_SERVICE_ACKNOWLEDGE_EXTERNAL=true: detection sends the unredacted text there. Make sure of a legal basis (Art. 6 GDPR), a data processing agreement (Art. 28) and, outside the EU/EEA, a transfer mechanism (Art. 44 ff.).`,
|
|
283
|
+
];
|
|
284
|
+
}
|
|
285
|
+
if (model.location === ModelLocation.OnPremise && endpoint?.trim().toLowerCase().startsWith('http://') === true) {
|
|
286
|
+
return [
|
|
287
|
+
'warning',
|
|
288
|
+
'model',
|
|
289
|
+
'The model server (PII_SERVICE_MODEL_URL) is reached over plain HTTP: the unredacted text crosses the network unencrypted. Use https://.',
|
|
290
|
+
];
|
|
291
|
+
}
|
|
292
|
+
return ['ok', 'model', `Model provider ${model.provider} (${model.location}).`];
|
|
293
|
+
}
|
|
294
|
+
/** The tables the service uses (it always uses the default names). */
|
|
295
|
+
const VAULT_TABLE = 'pii_shield_vault';
|
|
296
|
+
const TYPES_TABLE = 'pii_shield_learned_types';
|
|
297
|
+
async function connectChecks(get, plan) {
|
|
298
|
+
const findings = [];
|
|
299
|
+
const add = (severity, check, message) => {
|
|
300
|
+
findings.push(Object.freeze({ severity, check, message }));
|
|
301
|
+
};
|
|
302
|
+
const connection = connections(get, { failFast: true, onPoolError: () => undefined });
|
|
303
|
+
try {
|
|
304
|
+
if (plan.postgres) {
|
|
305
|
+
await checkPostgres(connection, plan, add);
|
|
306
|
+
}
|
|
307
|
+
if (plan.redis) {
|
|
308
|
+
await checkRedis(connection, plan, add);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
finally {
|
|
312
|
+
await connection.closeQuietly();
|
|
313
|
+
}
|
|
314
|
+
return findings;
|
|
315
|
+
}
|
|
316
|
+
async function checkPostgres(connection, plan, add) {
|
|
317
|
+
let query;
|
|
318
|
+
try {
|
|
319
|
+
query = await connection.postgres();
|
|
320
|
+
const { rows } = await query('SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()', []);
|
|
321
|
+
add('ok', 'connect-postgres', 'PostgreSQL answers.');
|
|
322
|
+
const ssl = rows[0]?.ssl === true;
|
|
323
|
+
if (ssl) {
|
|
324
|
+
add('ok', 'connect-postgres-tls', 'The database connection is encrypted (TLS).');
|
|
325
|
+
}
|
|
326
|
+
else if (!plan.localDatabase) {
|
|
327
|
+
add('error', 'connect-postgres-tls', 'The connection to the database is not encrypted.');
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
catch (e) {
|
|
331
|
+
add('error', 'connect-postgres', `PostgreSQL cannot be reached: ${connection.safeMessage(e)}`);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const { PostgresCustomEntityStore, PostgresVaultStorage } = await import('../postgres/index.js');
|
|
335
|
+
const rights = async (table) => {
|
|
336
|
+
const { rows } = await query("SELECT has_table_privilege($1, 'SELECT') AS s, has_table_privilege($1, 'INSERT') AS i, has_table_privilege($1, 'UPDATE') AS u, has_table_privilege($1, 'DELETE') AS d", [table]);
|
|
337
|
+
const row = (rows[0] ?? {});
|
|
338
|
+
return [
|
|
339
|
+
['s', 'SELECT'],
|
|
340
|
+
['i', 'INSERT'],
|
|
341
|
+
['u', 'UPDATE'],
|
|
342
|
+
['d', 'DELETE'],
|
|
343
|
+
]
|
|
344
|
+
.filter(([column]) => row[column] !== true)
|
|
345
|
+
.map(([, right]) => right);
|
|
346
|
+
};
|
|
347
|
+
const tables = [];
|
|
348
|
+
if (plan.vaultStore === 'postgres') {
|
|
349
|
+
tables.push([
|
|
350
|
+
'connect-vault-table',
|
|
351
|
+
VAULT_TABLE,
|
|
352
|
+
async () => {
|
|
353
|
+
await new PostgresVaultStorage({ query }).get('pii-shield-doctor-check');
|
|
354
|
+
if (plan.purgeInterval === 0) {
|
|
355
|
+
const { rows } = await query(`SELECT count(*) AS n FROM "${VAULT_TABLE}" WHERE expires_at <= now()`, []);
|
|
356
|
+
const expired = Number(rows[0]?.n ?? 0);
|
|
357
|
+
if (expired > 0) {
|
|
358
|
+
add('warning', 'vault-purge', `${String(expired)} expired vault row(s) are waiting to be deleted.`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
},
|
|
362
|
+
]);
|
|
363
|
+
}
|
|
364
|
+
if (plan.learnedStore === 'postgres') {
|
|
365
|
+
tables.push([
|
|
366
|
+
'connect-learned-table',
|
|
367
|
+
TYPES_TABLE,
|
|
368
|
+
async () => {
|
|
369
|
+
await learnedTypesFinding(new PostgresCustomEntityStore({ query }), plan, add);
|
|
370
|
+
},
|
|
371
|
+
]);
|
|
372
|
+
}
|
|
373
|
+
for (const [check, table, readTable] of tables) {
|
|
374
|
+
try {
|
|
375
|
+
await readTable();
|
|
376
|
+
}
|
|
377
|
+
catch (e) {
|
|
378
|
+
add('error', check, `The table ${table} cannot be read: ${connection.safeMessage(e)}. Create the tables with "pii-shield db-schema".`);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
const missing = await rights(table);
|
|
383
|
+
if (missing.length === 0) {
|
|
384
|
+
add('ok', check, `The table ${table} exists; the role may read and write it.`);
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
add('error', check, `The database role lacks ${missing.join(', ')} on ${table}.`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
catch (e) {
|
|
391
|
+
add('warning', check, `The rights on ${table} cannot be checked: ${connection.safeMessage(e)}`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async function checkRedis(connection, plan, add) {
|
|
396
|
+
let client;
|
|
397
|
+
try {
|
|
398
|
+
client = await connection.redis();
|
|
399
|
+
await client.ping();
|
|
400
|
+
add('ok', 'connect-redis', 'Redis answers.');
|
|
401
|
+
}
|
|
402
|
+
catch (e) {
|
|
403
|
+
add('error', 'connect-redis', `Redis cannot be reached: ${connection.safeMessage(e)}`);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
if (plan.learnedStore === 'redis') {
|
|
407
|
+
try {
|
|
408
|
+
await learnedTypesFinding(new KeyValueCustomEntityStore(client), plan, add);
|
|
409
|
+
}
|
|
410
|
+
catch (e) {
|
|
411
|
+
add('error', 'connect-learned-redis', `The learned types cannot be read: ${connection.safeMessage(e)}`);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
async function learnedTypesFinding(store, plan, add) {
|
|
416
|
+
const types = await store.all();
|
|
417
|
+
if (plan.keepExamples === false) {
|
|
418
|
+
const withExamples = types.filter((t) => t.pattern !== null && t.examples.length > 0).length;
|
|
419
|
+
if (withExamples > 0) {
|
|
420
|
+
add('warning', 'learned-examples', `${String(withExamples)} stored learned type(s) still hold examples; EntityLearner.dropExamples() removes them.`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
add('info', 'learned-types', `${String(types.length)} learned type(s) stored.`);
|
|
424
|
+
}
|
|
425
|
+
/** The findings as text, one line each, and a summary. */
|
|
426
|
+
export function formatFindings(findings) {
|
|
427
|
+
const counts = countFindings(findings);
|
|
428
|
+
const lines = findings.map((f) => `${f.severity.padEnd(8)}${f.check.padEnd(24)}${f.message}`);
|
|
429
|
+
lines.push('', `${String(counts.error)} error(s), ${String(counts.warning)} warning(s), ${String(counts.info)} note(s), ${String(counts.ok)} ok`);
|
|
430
|
+
return `${lines.join('\n')}\n`;
|
|
431
|
+
}
|
|
432
|
+
export function countFindings(findings) {
|
|
433
|
+
const counts = { error: 0, warning: 0, info: 0, ok: 0 };
|
|
434
|
+
for (const { severity } of findings) {
|
|
435
|
+
counts[severity]++;
|
|
436
|
+
}
|
|
437
|
+
return counts;
|
|
438
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the service's environment variables (docs/server.md). serviceFromEnv() and the configuration
|
|
3
|
+
* check (`pii-shield doctor`, checkServiceConfig()) share these functions, so they cannot drift apart.
|
|
4
|
+
* Every error is a ConfigError whose message names the variable, never its value.
|
|
5
|
+
*/
|
|
6
|
+
import { type DetectionModel, type ModelLocation } from '../model/model-detector.js';
|
|
7
|
+
import { type ModelProvider } from './model-providers.js';
|
|
8
|
+
/** A configuration problem; the message names the variable, never a secret. */
|
|
9
|
+
export declare class ConfigError extends Error {
|
|
10
|
+
readonly name = "ConfigError";
|
|
11
|
+
}
|
|
12
|
+
export type Env = Readonly<Record<string, string | undefined>>;
|
|
13
|
+
/** A variable's value; unset and empty both give undefined. */
|
|
14
|
+
export type EnvGetter = (name: string) => string | undefined;
|
|
15
|
+
export declare function envGetter(env: Env): EnvGetter;
|
|
16
|
+
export declare function integer(value: string | undefined, name: string, fallback: number, min?: number): number;
|
|
17
|
+
export interface VaultKeys {
|
|
18
|
+
/** Undefined when PII_SERVICE_VAULT_KEY is not set (the service then uses a random key, memory only). */
|
|
19
|
+
key: Uint8Array | undefined;
|
|
20
|
+
previousKeys: Uint8Array[];
|
|
21
|
+
}
|
|
22
|
+
/** PII_SERVICE_VAULT_KEY decoded, or undefined when not set. The caller wipes it after use. */
|
|
23
|
+
export declare function readVaultKey(get: EnvGetter): Uint8Array | undefined;
|
|
24
|
+
/** PII_SERVICE_VAULT_PREVIOUS_KEYS decoded (`[]` when not set). The caller wipes them after use. */
|
|
25
|
+
export declare function readPreviousVaultKeys(get: EnvGetter, env: Env): Uint8Array[];
|
|
26
|
+
/** Both keys, decoded. The caller wipes them after use. */
|
|
27
|
+
export declare function readVaultKeys(get: EnvGetter, env: Env): VaultKeys;
|
|
28
|
+
export type VaultStoreKind = 'memory' | 'redis' | 'postgres';
|
|
29
|
+
export declare function readVaultStore(get: EnvGetter): VaultStoreKind;
|
|
30
|
+
/** A persistent vault store needs a fixed key: a random one could not read the entries after a restart. */
|
|
31
|
+
export declare function assertVaultKeyFor(store: VaultStoreKind, hasKey: boolean): void;
|
|
32
|
+
export declare function readVaultTtl(get: EnvGetter): number;
|
|
33
|
+
/** Seconds between purges of expired Postgres vault rows; 0 = off. */
|
|
34
|
+
export declare function readPurgeInterval(get: EnvGetter): number;
|
|
35
|
+
export type LearnedStoreKind = 'file' | 'memory' | 'redis' | 'postgres';
|
|
36
|
+
export declare function readLearnedStore(get: EnvGetter): {
|
|
37
|
+
kind: LearnedStoreKind;
|
|
38
|
+
file: string | undefined;
|
|
39
|
+
};
|
|
40
|
+
export declare function readKeepExamples(get: EnvGetter): boolean;
|
|
41
|
+
export declare function readRedisUrl(get: EnvGetter): string;
|
|
42
|
+
/** PII_SERVICE_DATABASE_URL, checked to be a postgres URL (the message never quotes it: it holds the password). */
|
|
43
|
+
export declare function readDatabaseUrl(get: EnvGetter): string;
|
|
44
|
+
export interface ModelConfig {
|
|
45
|
+
provider: ModelProvider;
|
|
46
|
+
model: DetectionModel;
|
|
47
|
+
location: ModelLocation;
|
|
48
|
+
acknowledged: boolean;
|
|
49
|
+
/** Milliseconds per detection. */
|
|
50
|
+
timeout: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The model provider (PII_SERVICE_MODEL_PROVIDER and its settings), or undefined without one. Refuses an
|
|
54
|
+
* external provider without PII_SERVICE_ACKNOWLEDGE_EXTERNAL=true.
|
|
55
|
+
*/
|
|
56
|
+
export declare function readModel(get: EnvGetter): ModelConfig | undefined;
|
|
57
|
+
/** Listen address and request limits. */
|
|
58
|
+
export declare function readListen(get: EnvGetter): {
|
|
59
|
+
host: string;
|
|
60
|
+
port: number;
|
|
61
|
+
maxBodyBytes: number;
|
|
62
|
+
};
|