@eagleoutice/flowr 2.16.7 → 2.17.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/README.md +16 -10
- package/abstract-interpretation/absint-inference.d.ts +17 -1
- package/abstract-interpretation/absint-inference.js +118 -3
- package/abstract-interpretation/data-frame/arguments.d.ts +11 -1
- package/abstract-interpretation/data-frame/arguments.js +12 -0
- package/abstract-interpretation/domains/lattice.d.ts +2 -0
- package/abstract-interpretation/domains/lattice.js +0 -6
- package/abstract-interpretation/domains/multi-value-state-domain.d.ts +2 -1
- package/abstract-interpretation/domains/multi-value-state-domain.js +7 -3
- package/abstract-interpretation/domains/partial-product-domain.js +2 -1
- package/abstract-interpretation/domains/state-abstract-domain.d.ts +6 -3
- package/abstract-interpretation/domains/state-abstract-domain.js +13 -7
- package/abstract-interpretation/domains/state-domain.d.ts +4 -0
- package/config.js +1 -1
- package/control-flow/useless-loop.js +10 -8
- package/data/r-primitives.generated.d.ts +1 -0
- package/data/r-primitives.generated.js +9 -0
- package/data/sigdb/sigdb.remote.json +110 -110
- package/dataflow/environments/identifier.d.ts +1 -1
- package/dataflow/environments/query-fn-props.d.ts +9 -3
- package/dataflow/environments/query-fn-props.js +13 -5
- package/dataflow/environments/reference-to-maybe.js +1 -6
- package/dataflow/fn/class-declaration.js +1 -8
- package/dataflow/graph/dataflowgraph-builder.d.ts +4 -4
- package/dataflow/graph/df-helper.d.ts +2 -0
- package/dataflow/graph/df-helper.js +7 -0
- package/dataflow/graph/graph.js +3 -10
- package/dataflow/graph/vertex.d.ts +1 -1
- package/dataflow/hooks.d.ts +1 -1
- package/dataflow/info.d.ts +3 -3
- package/dataflow/internal/linker.js +1 -1
- package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +2 -2
- package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +1 -1
- package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +1 -7
- package/dataflow/processor.d.ts +1 -1
- package/documentation/wiki-linter.js +29 -0
- package/documentation/wiki-query.js +20 -1
- package/linter/linter-executor.js +2 -1
- package/linter/linter-rules.d.ts +65 -0
- package/linter/linter-rules.js +5 -1
- package/linter/rules/cmd-check/global-environment-modification.d.ts +14 -1
- package/linter/rules/cmd-check/global-environment-modification.js +15 -7
- package/linter/rules/no-leaked-credentials.d.ts +1 -0
- package/linter/rules/no-leaked-credentials.js +3 -3
- package/linter/rules/process-state-in-session.d.ts +71 -0
- package/linter/rules/process-state-in-session.js +267 -0
- package/linter/rules/secret-exfiltration.d.ts +80 -0
- package/linter/rules/secret-exfiltration.js +183 -0
- package/package.json +1 -1
- package/project/flowr-analyzer.d.ts +6 -0
- package/project/flowr-analyzer.js +4 -0
- package/project/plugins/file-plugins/files/flowr-namespace-file.d.ts +2 -0
- package/project/plugins/file-plugins/files/flowr-namespace-file.js +22 -3
- package/project/sigdb/decompress.d.ts +4 -0
- package/project/sigdb/decompress.js +60 -25
- package/project/sigdb/manifest.d.ts +1 -1
- package/project/sigdb/manifest.js +2 -5
- package/project/sigdb/reader.js +15 -6
- package/project/sigdb/sigdb-download.d.ts +3 -7
- package/project/sigdb/sigdb-download.js +71 -72
- package/queries/catalog/taint-query/taint-query-executor.d.ts +7 -0
- package/queries/catalog/taint-query/taint-query-executor.js +30 -0
- package/queries/catalog/taint-query/taint-query-format.d.ts +29 -0
- package/queries/catalog/taint-query/taint-query-format.js +124 -0
- package/queries/query.d.ts +12 -1
- package/queries/query.js +2 -0
- package/taint-analysis/builder/domain.d.ts +14 -0
- package/taint-analysis/builder/domain.js +69 -0
- package/taint-analysis/builder/report-template.d.ts +50 -0
- package/taint-analysis/builder/report-template.js +46 -0
- package/taint-analysis/builder/taint-analysis-definition.d.ts +108 -0
- package/taint-analysis/builder/taint-analysis-definition.js +128 -0
- package/taint-analysis/builder/taint-analysis.d.ts +124 -0
- package/taint-analysis/builder/taint-analysis.js +93 -0
- package/taint-analysis/builtin-index-bridge.d.ts +20 -0
- package/taint-analysis/builtin-index-bridge.js +48 -0
- package/taint-analysis/eval/eval.d.ts +1 -0
- package/taint-analysis/eval/eval.js +124 -0
- package/taint-analysis/eval/instrumentation.d.ts +59 -0
- package/taint-analysis/eval/instrumentation.js +124 -0
- package/taint-analysis/finite-domain.d.ts +41 -0
- package/taint-analysis/finite-domain.js +118 -0
- package/taint-analysis/function-categories.d.ts +31 -0
- package/taint-analysis/function-categories.js +61 -0
- package/taint-analysis/logger.d.ts +1 -0
- package/taint-analysis/logger.js +6 -0
- package/taint-analysis/predefined/determinism.d.ts +6 -0
- package/taint-analysis/predefined/determinism.js +14 -0
- package/taint-analysis/predefined/normalization.d.ts +17 -0
- package/taint-analysis/predefined/normalization.js +150 -0
- package/taint-analysis/predefined/predefined.d.ts +12 -0
- package/taint-analysis/predefined/predefined.js +18 -0
- package/taint-analysis/predefined/randomness-analysis.d.ts +6 -0
- package/taint-analysis/predefined/randomness-analysis.js +124 -0
- package/taint-analysis/predefined/secret-analysis.d.ts +77 -0
- package/taint-analysis/predefined/secret-analysis.js +165 -0
- package/taint-analysis/predefined/security-analysis.d.ts +7 -0
- package/taint-analysis/predefined/security-analysis.js +91 -0
- package/taint-analysis/taint-mapping.d.ts +86 -0
- package/taint-analysis/taint-mapping.js +70 -0
- package/taint-analysis/taint-resolve.d.ts +26 -0
- package/taint-analysis/taint-resolve.js +86 -0
- package/taint-analysis/taint-visitor.d.ts +80 -0
- package/taint-analysis/taint-visitor.js +82 -0
- package/util/flowr-version.d.ts +1 -1
- package/util/flowr-version.js +2 -2
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type LintingResult, LintingRuleCertainty } from '../linter-format';
|
|
2
|
+
import type { MergeableRecord } from '../../util/objects';
|
|
3
|
+
import { LintingRuleTag } from '../linter-tags';
|
|
4
|
+
import { Identifier } from '../../dataflow/environments/identifier';
|
|
5
|
+
import type { ReadonlyFlowrAnalysisProvider } from '../../project/flowr-analyzer';
|
|
6
|
+
import { InputType } from '../../queries/catalog/input-sources-query/input-types';
|
|
7
|
+
import { FileTrust, type SecretSink, SecretSinkClass } from '../../taint-analysis/predefined/secret-analysis';
|
|
8
|
+
/** How a secret leaves the process, see {@link Leaks} */
|
|
9
|
+
export declare enum SecretLeak {
|
|
10
|
+
Exfiltration = "exfiltration",
|
|
11
|
+
Leakage = "leakage",
|
|
12
|
+
Url = "url",
|
|
13
|
+
Files = "files",
|
|
14
|
+
Process = "process",
|
|
15
|
+
Llm = "llm"
|
|
16
|
+
}
|
|
17
|
+
export type SecretLeakSeverity = 'high' | 'medium' | 'low';
|
|
18
|
+
export interface SecretExfiltrationResult extends LintingResult {
|
|
19
|
+
readonly function: string;
|
|
20
|
+
readonly sink: SecretSinkClass;
|
|
21
|
+
readonly leak: SecretLeak;
|
|
22
|
+
readonly severity: SecretLeakSeverity;
|
|
23
|
+
}
|
|
24
|
+
export interface SecretExfiltrationConfig extends MergeableRecord {
|
|
25
|
+
/** environment variable names that hold credentials (case-insensitive) */
|
|
26
|
+
readonly credentialNamePattern: string;
|
|
27
|
+
/** literals that are credentials, as in `no-leaked-credentials` */
|
|
28
|
+
readonly credentialValuePattern: string;
|
|
29
|
+
/** extra functions returning secrets */
|
|
30
|
+
readonly sources: readonly Identifier[];
|
|
31
|
+
/** extra functions whose result is never secret */
|
|
32
|
+
readonly declassifiers: readonly Identifier[];
|
|
33
|
+
/** where secrets leave the process */
|
|
34
|
+
readonly sinks: readonly SecretSink[];
|
|
35
|
+
/** low-severity leaks to report */
|
|
36
|
+
readonly optIn: readonly SecretLeak[];
|
|
37
|
+
/** input types that make a destination untrusted, including files (see `fileTrust` for what they hold) */
|
|
38
|
+
readonly controlledInputs: readonly InputType[];
|
|
39
|
+
/** how far the content of files is trusted not to hold secrets; untrusted content gives uncertain results */
|
|
40
|
+
readonly fileTrust: FileTrust;
|
|
41
|
+
/** paths of files holding secrets, in addition to credential files like `.Renviron` */
|
|
42
|
+
readonly secretFiles: string;
|
|
43
|
+
/** paths of files trusted to hold no secrets, an empty pattern trusts none */
|
|
44
|
+
readonly trustedFiles: string;
|
|
45
|
+
}
|
|
46
|
+
export interface SecretExfiltrationMetadata extends MergeableRecord {
|
|
47
|
+
/** sink calls a secret reaches */
|
|
48
|
+
readonly secretSinkCalls: number;
|
|
49
|
+
}
|
|
50
|
+
export declare const SECRET_EXFILTRATION: {
|
|
51
|
+
readonly createSearch: () => import("../../search/flowr-search-builder").FlowrSearchBuilder<"from", [], import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElements<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElement<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>;
|
|
52
|
+
readonly processSearchResult: (_elements: import("../../search/flowr-search").FlowrSearchElements<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElement<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>, config: SecretExfiltrationConfig, data: ReadonlyFlowrAnalysisProvider<import("../..").KnownParser>) => Promise<{
|
|
53
|
+
results: SecretExfiltrationResult[];
|
|
54
|
+
'.meta': {
|
|
55
|
+
secretSinkCalls: number;
|
|
56
|
+
};
|
|
57
|
+
}>;
|
|
58
|
+
readonly prettyPrint: {
|
|
59
|
+
readonly query: (r: SecretExfiltrationResult, metadata: unknown) => string;
|
|
60
|
+
readonly full: (r: SecretExfiltrationResult, metadata: unknown) => string;
|
|
61
|
+
};
|
|
62
|
+
readonly info: {
|
|
63
|
+
readonly name: "Secret Exfiltration";
|
|
64
|
+
readonly tags: readonly [LintingRuleTag.Bug, LintingRuleTag.Security, LintingRuleTag.Shiny];
|
|
65
|
+
readonly certainty: LintingRuleCertainty.BestEffort;
|
|
66
|
+
readonly description: "Finds secrets (environment, keyrings, config, credential files) sent to untrusted hosts, the browser, or logs, and optionally into urls, files, other processes, or language models.";
|
|
67
|
+
readonly defaultConfig: () => {
|
|
68
|
+
credentialNamePattern: string;
|
|
69
|
+
credentialValuePattern: string;
|
|
70
|
+
sources: never[];
|
|
71
|
+
declassifiers: never[];
|
|
72
|
+
sinks: readonly SecretSink[];
|
|
73
|
+
optIn: never[];
|
|
74
|
+
controlledInputs: (InputType.Parameter | InputType.File | InputType.Network | InputType.CommandLine | InputType.User)[];
|
|
75
|
+
fileTrust: FileTrust.None;
|
|
76
|
+
secretFiles: string;
|
|
77
|
+
trustedFiles: string;
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SECRET_EXFILTRATION = exports.SecretLeak = void 0;
|
|
4
|
+
const linter_format_1 = require("../linter-format");
|
|
5
|
+
const flowr_search_builder_1 = require("../../search/flowr-search-builder");
|
|
6
|
+
const range_1 = require("../../util/range");
|
|
7
|
+
const linter_tags_1 = require("../linter-tags");
|
|
8
|
+
const identifier_1 = require("../../dataflow/environments/identifier");
|
|
9
|
+
const graph_1 = require("../../dataflow/graph/graph");
|
|
10
|
+
const vertex_1 = require("../../dataflow/graph/vertex");
|
|
11
|
+
const edge_1 = require("../../dataflow/graph/edge");
|
|
12
|
+
const df_helper_1 = require("../../dataflow/graph/df-helper");
|
|
13
|
+
const r_function_call_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
|
|
14
|
+
const r_symbol_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
|
|
15
|
+
const r_argument_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
|
|
16
|
+
const arguments_1 = require("../../abstract-interpretation/data-frame/arguments");
|
|
17
|
+
const input_types_1 = require("../../queries/catalog/input-sources-query/input-types");
|
|
18
|
+
const parse_1 = require("../../slicing/criterion/parse");
|
|
19
|
+
const resolve_helper_1 = require("../../dataflow/environments/resolve-helper");
|
|
20
|
+
const config_1 = require("../../config");
|
|
21
|
+
const taint_mapping_1 = require("../../taint-analysis/taint-mapping");
|
|
22
|
+
const taint_visitor_1 = require("../../taint-analysis/taint-visitor");
|
|
23
|
+
const secret_analysis_1 = require("../../taint-analysis/predefined/secret-analysis");
|
|
24
|
+
const no_leaked_credentials_1 = require("./no-leaked-credentials");
|
|
25
|
+
const security_analysis_1 = require("../../taint-analysis/predefined/security-analysis");
|
|
26
|
+
/** How a secret leaves the process, see {@link Leaks} */
|
|
27
|
+
var SecretLeak;
|
|
28
|
+
(function (SecretLeak) {
|
|
29
|
+
SecretLeak["Exfiltration"] = "exfiltration";
|
|
30
|
+
SecretLeak["Leakage"] = "leakage";
|
|
31
|
+
SecretLeak["Url"] = "url";
|
|
32
|
+
SecretLeak["Files"] = "files";
|
|
33
|
+
SecretLeak["Process"] = "process";
|
|
34
|
+
SecretLeak["Llm"] = "llm";
|
|
35
|
+
})(SecretLeak || (exports.SecretLeak = SecretLeak = {}));
|
|
36
|
+
/** severity and message per leak, low ones need opt-in */
|
|
37
|
+
const Leaks = {
|
|
38
|
+
[SecretLeak.Exfiltration]: { severity: 'high', does: 'sends a secret to a destination others control' },
|
|
39
|
+
[SecretLeak.Leakage]: { severity: 'medium', does: 'shows a secret' },
|
|
40
|
+
[SecretLeak.Url]: { severity: 'low', does: 'puts a secret into a url' },
|
|
41
|
+
[SecretLeak.Files]: { severity: 'low', does: 'writes a secret to a file' },
|
|
42
|
+
[SecretLeak.Process]: { severity: 'low', does: 'passes a secret to another process' },
|
|
43
|
+
[SecretLeak.Llm]: { severity: 'low', does: 'sends a secret to a language model' }
|
|
44
|
+
};
|
|
45
|
+
/** request builders passing their destination on */
|
|
46
|
+
const RequestBuilder = /^(?:request|req_\w+)$/;
|
|
47
|
+
const StandardStreams = new Set(['stdout', 'stderr']);
|
|
48
|
+
const MaxDestinationHops = 5;
|
|
49
|
+
const argumentAt = (call, at, info) => at === undefined ? undefined : r_argument_1.RArgument.valueOf((0, arguments_1.getFunctionArgument)((0, arguments_1.getVertexArguments)(call, info.idMap), at, info))?.info.id;
|
|
50
|
+
function requestBuilder(vertex) {
|
|
51
|
+
return vertex_1.DfgVertex.isFunctionCall(vertex) && RequestBuilder.test(identifier_1.Identifier.getName(vertex.name)) ? vertex : undefined;
|
|
52
|
+
}
|
|
53
|
+
/** the expression naming the destination of a sink call, through request builders and the variables holding them */
|
|
54
|
+
function destinationOf(call, sink, info) {
|
|
55
|
+
const { graph, idMap } = info;
|
|
56
|
+
let id = argumentAt(call, sink.destination, info);
|
|
57
|
+
for (let i = 0; i < MaxDestinationHops && id !== undefined; i++) {
|
|
58
|
+
const first = requestBuilder(graph.getVertex(id))?.args.find(graph_1.FunctionArgument.isNotEmpty);
|
|
59
|
+
const next = r_symbol_1.RSymbol.is(idMap.get(id))
|
|
60
|
+
? df_helper_1.Dataflow.targetsOf(graph, id, edge_1.EdgeType.Reads).map(def => df_helper_1.Dataflow.assignedValueOf(def, graph)).find(v => v !== undefined && requestBuilder(graph.getVertex(v)) !== undefined)
|
|
61
|
+
: first && graph_1.FunctionArgument.getReference(first);
|
|
62
|
+
if (next === undefined) {
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
id = next;
|
|
66
|
+
}
|
|
67
|
+
return id;
|
|
68
|
+
}
|
|
69
|
+
/** whether a destination is controlled by others, uncertain as it stems from a parameter, or trusted */
|
|
70
|
+
async function classifyDestination(data, id, controlled) {
|
|
71
|
+
const criterion = parse_1.SlicingCriterion.fromId(id);
|
|
72
|
+
const types = new Set((await data.query([{ type: 'input-sources', criterion }]))['input-sources']?.results[criterion]?.flatMap(s => s.types));
|
|
73
|
+
if (controlled.some(t => t !== input_types_1.InputType.Parameter && types.has(t))) {
|
|
74
|
+
return 'controlled';
|
|
75
|
+
}
|
|
76
|
+
return types.has(input_types_1.InputType.Parameter) && controlled.includes(input_types_1.InputType.Parameter) ? 'parameter' : 'trusted';
|
|
77
|
+
}
|
|
78
|
+
async function leakOf(data, call, untrusted, info, config) {
|
|
79
|
+
const fixed = call.sink.class === secret_analysis_1.SecretSinkClass.Browser ? SecretLeak.Leakage : [SecretLeak.Files, SecretLeak.Process, SecretLeak.Llm].find(l => l === call.sink.class);
|
|
80
|
+
const file = info.idMap.get(argumentAt(call.call, call.sink.file, info) ?? '');
|
|
81
|
+
if (fixed !== undefined || call.sink.class === secret_analysis_1.SecretSinkClass.Logs) {
|
|
82
|
+
return { leak: fixed ?? (file !== undefined && !r_function_call_1.RFunctionCall.isNamed(file, StandardStreams) && file.lexeme !== '""' ? SecretLeak.Files : SecretLeak.Leakage), certain: true };
|
|
83
|
+
}
|
|
84
|
+
const destination = destinationOf(call.call, call.sink, info);
|
|
85
|
+
const trust = untrusted ? 'controlled' : destination === undefined ? 'trusted' : await classifyDestination(data, destination, config.controlledInputs);
|
|
86
|
+
if (trust !== 'trusted') {
|
|
87
|
+
return { leak: SecretLeak.Exfiltration, certain: trust === 'controlled' };
|
|
88
|
+
}
|
|
89
|
+
const urlArgs = [argumentAt(call.call, call.sink.destination, info), argumentAt(call.call, { pos: -1, name: 'query' }, info)];
|
|
90
|
+
const inUrl = [...call.secret].some(([id, kind]) => kind !== secret_analysis_1.Credential && (call.sink.inUrl || urlArgs.includes(id)));
|
|
91
|
+
return call.sink.class === secret_analysis_1.SecretSinkClass.Network && inUrl ? { leak: SecretLeak.Url, certain: true } : undefined;
|
|
92
|
+
}
|
|
93
|
+
exports.SECRET_EXFILTRATION = {
|
|
94
|
+
createSearch: () => flowr_search_builder_1.Q.from([]),
|
|
95
|
+
processSearchResult: async (_elements, config, data) => {
|
|
96
|
+
const literal = new RegExp(config.credentialValuePattern);
|
|
97
|
+
const info = { graph: (await data.dataflow()).graph, idMap: (await data.normalize()).idMap, full: true, resolve: config_1.VariableResolve.Alias, ctx: data.inspectContext() };
|
|
98
|
+
const calls = new Map();
|
|
99
|
+
const untrusted = new Set();
|
|
100
|
+
const analysis = (0, secret_analysis_1.createSecretAnalysis)({
|
|
101
|
+
credentialNamePattern: new RegExp(config.credentialNamePattern, 'i'),
|
|
102
|
+
sources: config.sources,
|
|
103
|
+
declassifiers: config.declassifiers,
|
|
104
|
+
sinks: config.sinks,
|
|
105
|
+
fileTrust: config.fileTrust,
|
|
106
|
+
secretFiles: config.secretFiles === '' ? undefined : new RegExp(config.secretFiles),
|
|
107
|
+
trustedFiles: config.trustedFiles === '' ? undefined : new RegExp(config.trustedFiles)
|
|
108
|
+
});
|
|
109
|
+
await data.taint().add(analysis).addPredefined('security').withHook(({ name, call, node, projectArg }) => {
|
|
110
|
+
const called = (0, taint_visitor_1.taintCallName)(call, node);
|
|
111
|
+
const sink = config.sinks.find(s => s.fns.some(fn => taint_mapping_1.TaintMapper.matches(fn, called)));
|
|
112
|
+
if (sink === undefined) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (name === security_analysis_1.securityAnalysis.name) {
|
|
116
|
+
const destination = destinationOf(call, sink, info);
|
|
117
|
+
const taint = destination === undefined ? undefined : projectArg(destination)?.value;
|
|
118
|
+
if (taint === security_analysis_1.UserInput || taint === security_analysis_1.NetworkInput || taint === security_analysis_1.FileInput) {
|
|
119
|
+
untrusted.add(call.id);
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const secret = new Map();
|
|
124
|
+
for (const id of call.args.map(graph_1.FunctionArgument.getReference)) {
|
|
125
|
+
if (id === undefined) {
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const taint = projectArg(id)?.value;
|
|
129
|
+
if (taint === secret_analysis_1.Secret || taint === secret_analysis_1.Credential || taint === secret_analysis_1.FileContent || (taint === secret_analysis_1.Response && sink.serializes)) {
|
|
130
|
+
secret.set(id, taint);
|
|
131
|
+
}
|
|
132
|
+
else if (literal.test(resolve_helper_1.Resolve.toSingleString(id, info) ?? '')) {
|
|
133
|
+
secret.set(id, secret_analysis_1.Secret);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (secret.size > 0) {
|
|
137
|
+
calls.set(call.id, { call, sink, secret });
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
calls.delete(call.id);
|
|
141
|
+
}
|
|
142
|
+
}).run();
|
|
143
|
+
const results = [];
|
|
144
|
+
for (const call of calls.values()) {
|
|
145
|
+
const leak = await leakOf(data, call, untrusted.has(call.call.id), info, config);
|
|
146
|
+
if (leak === undefined || (Leaks[leak.leak].severity === 'low' && !config.optIn.includes(leak.leak))) {
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const node = info.idMap.get(call.call.id);
|
|
150
|
+
const severity = call.sink.class === secret_analysis_1.SecretSinkClass.Browser ? 'high' : Leaks[leak.leak].severity;
|
|
151
|
+
results.push({
|
|
152
|
+
involvedId: call.call.id,
|
|
153
|
+
loc: range_1.SourceLocation.fromNode(node) ?? range_1.SourceLocation.invalid(),
|
|
154
|
+
certainty: leak.certain && [...call.secret.values()].some(k => k !== secret_analysis_1.FileContent) ? linter_format_1.LintingResultCertainty.Certain : linter_format_1.LintingResultCertainty.Uncertain,
|
|
155
|
+
function: identifier_1.Identifier.toString((0, taint_visitor_1.taintCallName)(call.call, node)),
|
|
156
|
+
sink: call.sink.class,
|
|
157
|
+
leak: leak.leak,
|
|
158
|
+
severity
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return { results, '.meta': { secretSinkCalls: calls.size } };
|
|
162
|
+
},
|
|
163
|
+
prettyPrint: (0, linter_format_1.prettyPrint)(result => `${result.function} ${Leaks[result.leak].does} (${result.severity}) at ${range_1.SourceLocation.format(result.loc)}`, result => `${result.function} ${Leaks[result.leak].does} (${result.leak} via ${result.sink}, severity ${result.severity}) at ${range_1.SourceLocation.format(result.loc)}`),
|
|
164
|
+
info: {
|
|
165
|
+
name: 'Secret Exfiltration',
|
|
166
|
+
tags: [linter_tags_1.LintingRuleTag.Bug, linter_tags_1.LintingRuleTag.Security, linter_tags_1.LintingRuleTag.Shiny],
|
|
167
|
+
certainty: linter_format_1.LintingRuleCertainty.BestEffort,
|
|
168
|
+
description: 'Finds secrets (environment, keyrings, config, credential files) sent to untrusted hosts, the browser, or logs, and optionally into urls, files, other processes, or language models.',
|
|
169
|
+
defaultConfig: () => ({
|
|
170
|
+
credentialNamePattern: secret_analysis_1.CredentialNamePattern.source,
|
|
171
|
+
credentialValuePattern: no_leaked_credentials_1.defaultCredentialValuePattern,
|
|
172
|
+
sources: [],
|
|
173
|
+
declassifiers: [],
|
|
174
|
+
sinks: secret_analysis_1.DefaultSecretSinks,
|
|
175
|
+
optIn: [],
|
|
176
|
+
controlledInputs: [input_types_1.InputType.User, input_types_1.InputType.Network, input_types_1.InputType.File, input_types_1.InputType.CommandLine, input_types_1.InputType.Parameter],
|
|
177
|
+
fileTrust: secret_analysis_1.FileTrust.None,
|
|
178
|
+
secretFiles: '',
|
|
179
|
+
trustedFiles: ''
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
//# sourceMappingURL=secret-exfiltration.js.map
|
package/package.json
CHANGED
|
@@ -17,6 +17,7 @@ import { fileProtocol } from '../r-bridge/retriever';
|
|
|
17
17
|
import type { FlowrFileProvider } from './context/flowr-file';
|
|
18
18
|
import type { Tree } from 'web-tree-sitter';
|
|
19
19
|
import type { CallGraph } from '../dataflow/graph/call-graph';
|
|
20
|
+
import { type TaintAnalysisBuilder } from '../taint-analysis/builder/taint-analysis';
|
|
20
21
|
import type { InvalidationEvent } from './cache/flowr-cache';
|
|
21
22
|
import type { GasOverrides } from '../gas';
|
|
22
23
|
import type { FnInfo } from '../dataflow/environments/query-fn-props';
|
|
@@ -160,6 +161,10 @@ export interface ReadonlyFlowrAnalysisProvider<Parser extends KnownParser = Know
|
|
|
160
161
|
* @param options - Bounds for this call, see {@link FlowrAnalysisOptions}.
|
|
161
162
|
*/
|
|
162
163
|
query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>, options?: FlowrAnalysisOptions): Promise<QueryResults<Types>>;
|
|
164
|
+
/**
|
|
165
|
+
* Access the taint analysis API for the request.
|
|
166
|
+
*/
|
|
167
|
+
taint<Names extends readonly string[] = []>(): TaintAnalysisBuilder<Names>;
|
|
163
168
|
/**
|
|
164
169
|
* Run a search on the current analysis.
|
|
165
170
|
* @param search - The search to run.
|
|
@@ -240,6 +245,7 @@ export declare class FlowrAnalyzer<Parser extends KnownParser = KnownParser> imp
|
|
|
240
245
|
peekCallGraph(): CallGraph | undefined;
|
|
241
246
|
query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>, options?: FlowrAnalysisOptions): Promise<QueryResults<Types>>;
|
|
242
247
|
runSearch<Search extends FlowrSearchLike>(search: Search, options?: FlowrAnalysisOptions): Promise<GetSearchElements<SearchOutput<Search>>>;
|
|
248
|
+
taint<Names extends readonly string[] = []>(): TaintAnalysisBuilder<Names>;
|
|
243
249
|
/**
|
|
244
250
|
* Free the cached analyses (including any WASM-backed parse trees) and close the parser.
|
|
245
251
|
* Closing is only required for an RShell/remote engine, but this also frees the cached parse trees.
|
|
@@ -8,6 +8,7 @@ const retriever_1 = require("../r-bridge/retriever");
|
|
|
8
8
|
const files_1 = require("../util/files");
|
|
9
9
|
const tree_sitter_normalize_1 = require("../r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize");
|
|
10
10
|
const tree_sitter_executor_1 = require("../r-bridge/lang-4.x/tree-sitter/tree-sitter-executor");
|
|
11
|
+
const taint_analysis_1 = require("../taint-analysis/builder/taint-analysis");
|
|
11
12
|
const vertex_1 = require("../dataflow/graph/vertex");
|
|
12
13
|
const df_helper_1 = require("../dataflow/graph/df-helper");
|
|
13
14
|
/**
|
|
@@ -169,6 +170,9 @@ class FlowrAnalyzer {
|
|
|
169
170
|
async runSearch(search, options) {
|
|
170
171
|
return this.ctx.gas.withGas(options?.gas, () => (0, flowr_search_executor_1.runSearch)(search, this));
|
|
171
172
|
}
|
|
173
|
+
taint() {
|
|
174
|
+
return taint_analysis_1.TaintAnalysis.create(this);
|
|
175
|
+
}
|
|
172
176
|
/**
|
|
173
177
|
* Free the cached analyses (including any WASM-backed parse trees) and close the parser.
|
|
174
178
|
* Closing is only required for an RShell/remote engine, but this also frees the cached parse trees.
|
|
@@ -9,6 +9,8 @@ export interface NamespaceInfo {
|
|
|
9
9
|
/**
|
|
10
10
|
* Names listed by `exportMethods()`: S4 methods the package registered for one of its classes, which is a
|
|
11
11
|
* different claim than an ordinary export (the package answers a generic, it does not define the function).
|
|
12
|
+
* As R's `loadNamespace`, this keeps only the non-primitive generics: a method on a primitive such as `+` or `[`
|
|
13
|
+
* binds nothing in the namespace, so `pkg::"+"` does not exist and the call stays with base.
|
|
12
14
|
* Only the context-parsed path ({@link parseNamespaceComplex}) tells these apart; the regex fallback folds
|
|
13
15
|
* them into {@link exportedFunctions}.
|
|
14
16
|
*/
|
|
@@ -14,6 +14,7 @@ const fold_1 = require("../../../../r-bridge/lang-4.x/ast/model/processing/fold"
|
|
|
14
14
|
const identifier_1 = require("../../../../dataflow/environments/identifier");
|
|
15
15
|
const assert_1 = require("../../../../util/assert");
|
|
16
16
|
const type_1 = require("../../../../r-bridge/lang-4.x/ast/model/type");
|
|
17
|
+
const r_primitives_generated_1 = require("../../../../data/r-primitives.generated");
|
|
17
18
|
const make_argument_1 = require("../../../../dataflow/internal/process/functions/call/argument/make-argument");
|
|
18
19
|
const range_1 = require("../../../../util/range");
|
|
19
20
|
const r_regex_1 = require("../../../../util/r-regex");
|
|
@@ -334,9 +335,15 @@ function handleUseDynLibCall(g, args) {
|
|
|
334
335
|
}
|
|
335
336
|
/** `exportClasses(A, B)` / `exportMethods(show, summary)`: a directive may list several names, and each goes to `into`. */
|
|
336
337
|
function handleS4ExportCall(g, args, into) {
|
|
337
|
-
|
|
338
|
+
const names = [];
|
|
339
|
+
pushUnquotedLexemes(names, args, r_string_1.RString.unquote);
|
|
340
|
+
g.current[into].push(...(into === 'exportedS4Methods' ? exportedGenerics(names) : names));
|
|
338
341
|
return g;
|
|
339
342
|
}
|
|
343
|
+
/** The `exportMethods()` names R exports: methods on a primitive generic bind nothing in the namespace. */
|
|
344
|
+
function exportedGenerics(names) {
|
|
345
|
+
return names.filter(n => !r_primitives_generated_1.RPrimitives.has(n));
|
|
346
|
+
}
|
|
340
347
|
const cleanLineCommentRegex = /^#.*$/gm;
|
|
341
348
|
/** A namespace that neither exports nor imports anything yet. */
|
|
342
349
|
function emptyNamespaceInfo() {
|
|
@@ -439,9 +446,21 @@ function splitNamespaceArgs(args) {
|
|
|
439
446
|
const names = [];
|
|
440
447
|
let depth = 0;
|
|
441
448
|
let start = 0;
|
|
449
|
+
let quote;
|
|
442
450
|
for (let i = 0; i <= args.length; i++) {
|
|
443
451
|
const c = args[i];
|
|
444
|
-
if (
|
|
452
|
+
if (quote !== undefined) {
|
|
453
|
+
if (c === '\\') {
|
|
454
|
+
i++;
|
|
455
|
+
}
|
|
456
|
+
else if (c === quote) {
|
|
457
|
+
quote = undefined;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
else if (c === '"' || c === '\'' || c === '`') {
|
|
461
|
+
quote = c;
|
|
462
|
+
}
|
|
463
|
+
else if (c === '(' || c === '[') {
|
|
445
464
|
depth++;
|
|
446
465
|
}
|
|
447
466
|
else if (c === ')' || c === ']') {
|
|
@@ -474,7 +493,7 @@ function parseNamespaceSimple(file) {
|
|
|
474
493
|
case 'exportClasses':
|
|
475
494
|
case 'exportMethods':
|
|
476
495
|
// a single directive may list several symbols, e.g. `exportMethods(show, summary)`
|
|
477
|
-
result.current.exportedFunctions.push(...splitNamespaceArgs(args));
|
|
496
|
+
result.current.exportedFunctions.push(...exportedGenerics(splitNamespaceArgs(args)));
|
|
478
497
|
break;
|
|
479
498
|
case 'S3method':
|
|
480
499
|
{
|
|
@@ -20,6 +20,8 @@ export declare function resolveSource(baseDir: string, relPath: string): string;
|
|
|
20
20
|
* volume at the cache dir to persist it).
|
|
21
21
|
*/
|
|
22
22
|
export declare function sigDbCacheDir(override?: string, create?: boolean): string;
|
|
23
|
+
/** a temp path next to `target`, unique even across containers sharing a volume */
|
|
24
|
+
export declare const uniqueTempPath: (target: string, ext: string) => string;
|
|
23
25
|
/** read the (small) header line of a possibly-compressed bundle without decompressing the whole thing */
|
|
24
26
|
export declare function readHeaderOf(source: string): Promise<Record<string, unknown> | undefined>;
|
|
25
27
|
/** where an index for a decompressed source comes from -- a caller-supplied one (e.g. a manifest) or the sibling `.idx` */
|
|
@@ -29,6 +31,8 @@ export interface EnsureOptions {
|
|
|
29
31
|
index?: SigDbIndex;
|
|
30
32
|
/** the source is not a seekable bundle (e.g. a shared dictionary file) -- decompress only, write no `.idx` */
|
|
31
33
|
indexless?: boolean;
|
|
34
|
+
/** the expected decompressed size */
|
|
35
|
+
bytes?: number;
|
|
32
36
|
}
|
|
33
37
|
/** whether a compressed source with the given content hash has already been unpacked into its decompressed cache */
|
|
34
38
|
export declare function isUnpacked(hash: string, cacheDir?: string): boolean;
|
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.isCompressed = void 0;
|
|
6
|
+
exports.uniqueTempPath = exports.isCompressed = void 0;
|
|
7
7
|
exports.parseHeader = parseHeader;
|
|
8
8
|
exports.sigDbStream = sigDbStream;
|
|
9
9
|
exports.resolveSource = resolveSource;
|
|
@@ -20,6 +20,7 @@ exports.ensurePlainSync = ensurePlainSync;
|
|
|
20
20
|
*/
|
|
21
21
|
const fs_1 = __importDefault(require("fs"));
|
|
22
22
|
const os_1 = __importDefault(require("os"));
|
|
23
|
+
const crypto_1 = require("crypto");
|
|
23
24
|
const path_1 = __importDefault(require("path"));
|
|
24
25
|
const readline_1 = __importDefault(require("readline"));
|
|
25
26
|
const promises_1 = require("stream/promises");
|
|
@@ -80,19 +81,30 @@ function sigDbCacheDir(override, create = true) {
|
|
|
80
81
|
?? (process.env.LOCALAPPDATA ? path_1.default.join(process.env.LOCALAPPDATA, 'flowr', 'cache') : undefined)
|
|
81
82
|
?? path_1.default.join(os_1.default.homedir?.() || os_1.default.tmpdir(), '.cache', 'flowr');
|
|
82
83
|
const dir = path_1.default.join(base, 'sigdb');
|
|
83
|
-
|
|
84
|
+
const tmp = path_1.default.join(os_1.default.tmpdir(), `flowr-sigdb-cache-${process.getuid?.() ?? os_1.default.userInfo().username}`);
|
|
85
|
+
if (isWritableDir(dir, create) || !(create || fs_1.default.existsSync(tmp))) {
|
|
84
86
|
return dir;
|
|
85
87
|
}
|
|
88
|
+
if (create) {
|
|
89
|
+
fs_1.default.mkdirSync(tmp, { recursive: true, mode: 0o700 });
|
|
90
|
+
}
|
|
91
|
+
return tmp;
|
|
92
|
+
}
|
|
93
|
+
function isWritableDir(dir, create) {
|
|
86
94
|
try {
|
|
87
|
-
|
|
88
|
-
|
|
95
|
+
if (create) {
|
|
96
|
+
fs_1.default.mkdirSync(dir, { recursive: true });
|
|
97
|
+
}
|
|
98
|
+
fs_1.default.accessSync(dir, fs_1.default.constants.W_OK);
|
|
99
|
+
return true;
|
|
89
100
|
}
|
|
90
101
|
catch {
|
|
91
|
-
|
|
92
|
-
fs_1.default.mkdirSync(tmp, { recursive: true });
|
|
93
|
-
return tmp;
|
|
102
|
+
return false;
|
|
94
103
|
}
|
|
95
104
|
}
|
|
105
|
+
/** a temp path next to `target`, unique even across containers sharing a volume */
|
|
106
|
+
const uniqueTempPath = (target, ext) => `${target}.${process.pid}-${(0, crypto_1.randomBytes)(6).toString('hex')}.${ext}`;
|
|
107
|
+
exports.uniqueTempPath = uniqueTempPath;
|
|
96
108
|
/** read the (small) header line of a possibly-compressed bundle without decompressing the whole thing */
|
|
97
109
|
async function readHeaderOf(source) {
|
|
98
110
|
if (!(0, exports.isCompressed)(source)) {
|
|
@@ -138,6 +150,26 @@ function writeCacheIndex(source, idx, index) {
|
|
|
138
150
|
}
|
|
139
151
|
fs_1.default.copyFileSync(srcIdx, idx);
|
|
140
152
|
}
|
|
153
|
+
function isCachedPlain(plain, idx, opts) {
|
|
154
|
+
try {
|
|
155
|
+
const size = fs_1.default.statSync(plain).size;
|
|
156
|
+
return (opts.bytes === undefined || size === opts.bytes) && (opts.indexless || fs_1.default.existsSync(idx));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function commitPlain(source, tmp, plain, idx, opts) {
|
|
163
|
+
const size = fs_1.default.statSync(tmp).size;
|
|
164
|
+
if (opts.bytes !== undefined && size !== opts.bytes) {
|
|
165
|
+
throw new Error(`decompressing ${source} gave ${size} bytes, expected ${opts.bytes}; the file is corrupt or does not match its manifest`);
|
|
166
|
+
}
|
|
167
|
+
fs_1.default.renameSync(tmp, plain);
|
|
168
|
+
if (!opts.indexless) {
|
|
169
|
+
writeCacheIndex(source, idx, opts.index);
|
|
170
|
+
}
|
|
171
|
+
return plain;
|
|
172
|
+
}
|
|
141
173
|
/**
|
|
142
174
|
* Ensure a seekable plain `.sigs.ndjson` (+ its `.idx`) exists for `source`, decompressing a `.br`/`.zst`/`.gz`
|
|
143
175
|
* once into a hash-keyed cache the first time and reusing it on every later startup. The index may be
|
|
@@ -149,20 +181,24 @@ async function ensurePlain(source, opts = {}) {
|
|
|
149
181
|
}
|
|
150
182
|
let hash = opts.hash;
|
|
151
183
|
if (hash === undefined) {
|
|
152
|
-
|
|
153
|
-
|
|
184
|
+
hash = (await readHeaderOf(source))?.content?.hash;
|
|
185
|
+
if (hash === undefined) {
|
|
186
|
+
const { size, mtimeMs } = fs_1.default.statSync(source);
|
|
187
|
+
hash = new hash_1.Hash53().update(`${source}\0${size}\0${mtimeMs}`).digest();
|
|
188
|
+
}
|
|
154
189
|
}
|
|
155
190
|
const { plain, idx } = cachePaths(hash, opts.cacheDir);
|
|
156
|
-
if (
|
|
191
|
+
if (isCachedPlain(plain, idx, opts)) {
|
|
157
192
|
return plain;
|
|
158
193
|
}
|
|
159
|
-
const tmp =
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
194
|
+
const tmp = (0, exports.uniqueTempPath)(plain, 'tmp');
|
|
195
|
+
try {
|
|
196
|
+
await (0, promises_1.pipeline)(decompressStream(source), fs_1.default.createWriteStream(tmp));
|
|
197
|
+
return commitPlain(source, tmp, plain, idx, opts);
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
fs_1.default.rmSync(tmp, { force: true });
|
|
164
201
|
}
|
|
165
|
-
return plain;
|
|
166
202
|
}
|
|
167
203
|
/** synchronous {@link ensurePlain} (blocking decompression); the supplied `hash` keys the decompress cache */
|
|
168
204
|
function ensurePlainSync(source, opts) {
|
|
@@ -170,17 +206,16 @@ function ensurePlainSync(source, opts) {
|
|
|
170
206
|
return source;
|
|
171
207
|
}
|
|
172
208
|
const { plain, idx } = cachePaths(opts.hash, opts.cacheDir);
|
|
173
|
-
if (
|
|
209
|
+
if (isCachedPlain(plain, idx, opts)) {
|
|
174
210
|
return plain;
|
|
175
211
|
}
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
212
|
+
const tmp = (0, exports.uniqueTempPath)(plain, 'tmp');
|
|
213
|
+
try {
|
|
214
|
+
fs_1.default.writeFileSync(tmp, (0, codec_1.decompressSyncFor)(source, fs_1.default.readFileSync(source)));
|
|
215
|
+
return commitPlain(source, tmp, plain, idx, opts);
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
fs_1.default.rmSync(tmp, { force: true });
|
|
183
219
|
}
|
|
184
|
-
return plain;
|
|
185
220
|
}
|
|
186
221
|
//# sourceMappingURL=decompress.js.map
|
|
@@ -59,7 +59,7 @@ export type SigDbScope = 'base' | 'current' | 'full';
|
|
|
59
59
|
export declare function sigDbBundleDirs(watched?: [string, number][]): string[];
|
|
60
60
|
/**
|
|
61
61
|
* Location of a bundled sigdb **manifest**, found by walking up from several roots (this module,
|
|
62
|
-
* `$FLOWR_SIGDB_DIR
|
|
62
|
+
* `$FLOWR_SIGDB_DIR`) across the dev (`src`), build (`dist`), and data-mount
|
|
63
63
|
* layouts. With no `scope` it returns the richest available (`full` > `current` > `base`), so a
|
|
64
64
|
* container that ships the full set uses it automatically while a plain npm install falls back to the
|
|
65
65
|
* bundled `base`. Node only (needs `fs`); pass `searchRoots` to override where it looks.
|
|
@@ -91,7 +91,7 @@ function sigDbBundleDirs(watched) {
|
|
|
91
91
|
return [];
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
|
-
/** roots to search for a bundled sigdb
|
|
94
|
+
/** roots to search for a bundled sigdb: this module and `$FLOWR_SIGDB_DIR` (path-delimiter separated) */
|
|
95
95
|
function sigDbSearchRoots(extra) {
|
|
96
96
|
const roots = [...(extra ?? [])];
|
|
97
97
|
const env = typeof process !== 'undefined' ? process.env?.FLOWR_SIGDB_DIR : undefined;
|
|
@@ -101,14 +101,11 @@ function sigDbSearchRoots(extra) {
|
|
|
101
101
|
if (typeof __dirname !== 'undefined') {
|
|
102
102
|
roots.push(__dirname);
|
|
103
103
|
}
|
|
104
|
-
if (typeof process !== 'undefined' && typeof process.cwd === 'function') {
|
|
105
|
-
roots.push(process.cwd());
|
|
106
|
-
}
|
|
107
104
|
return roots;
|
|
108
105
|
}
|
|
109
106
|
/**
|
|
110
107
|
* Location of a bundled sigdb **manifest**, found by walking up from several roots (this module,
|
|
111
|
-
* `$FLOWR_SIGDB_DIR
|
|
108
|
+
* `$FLOWR_SIGDB_DIR`) across the dev (`src`), build (`dist`), and data-mount
|
|
112
109
|
* layouts. With no `scope` it returns the richest available (`full` > `current` > `base`), so a
|
|
113
110
|
* container that ships the full set uses it automatically while a plain npm install falls back to the
|
|
114
111
|
* bundled `base`. Node only (needs `fs`); pass `searchRoots` to override where it looks.
|
package/project/sigdb/reader.js
CHANGED
|
@@ -31,6 +31,7 @@ const dict_1 = require("./dict");
|
|
|
31
31
|
const hash_1 = require("./hash");
|
|
32
32
|
const manifest_1 = require("./manifest");
|
|
33
33
|
const arrays_1 = require("../../util/collections/arrays");
|
|
34
|
+
const log_1 = require("../../util/log");
|
|
34
35
|
/** the run of names one `d` line (`["d", start, payload]`, newline-blob or legacy `string[]` form) adds */
|
|
35
36
|
function dictLineRun(json) {
|
|
36
37
|
const [, start, payload] = JSON.parse(json);
|
|
@@ -422,7 +423,7 @@ class SigDatabase {
|
|
|
422
423
|
if (opts.hash === undefined) {
|
|
423
424
|
throw new Error('openSyncFrom needs a hash to key the cache for a compressed source');
|
|
424
425
|
}
|
|
425
|
-
plain = (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index });
|
|
426
|
+
plain = (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index, bytes: opts.index?.byteCount });
|
|
426
427
|
}
|
|
427
428
|
return SigDatabase.openSync(plain, { index: opts.index, strings: opts.strings });
|
|
428
429
|
}
|
|
@@ -742,9 +743,17 @@ class SigDatabaseSet {
|
|
|
742
743
|
if (full.format !== manifest_1.SigDbManifestMagic) {
|
|
743
744
|
throw new Error(`not a ${manifest_1.SigDbManifestMagic} (got ${String(full.format)})`);
|
|
744
745
|
}
|
|
745
|
-
const
|
|
746
|
+
const selected = selectShards(full.shards, opts.includeShards, opts.excludeShards);
|
|
747
|
+
const present = (rel) => fs_1.default.existsSync((0, decompress_1.resolveSource)(baseDir, rel));
|
|
748
|
+
const active = selected.filter(s => {
|
|
749
|
+
const dict = s.dict === undefined ? undefined : full.dicts?.find(d => d.id === s.dict);
|
|
750
|
+
return present(s.path) && (dict === undefined || present(dict.path));
|
|
751
|
+
});
|
|
752
|
+
if (active.length < selected.length) {
|
|
753
|
+
log_1.log.warn(`sigdb: ${manifestFile} lacks the files of ${selected.length - active.length} shard(s) (${selected.filter(s => !active.includes(s)).map(s => s.path).join(', ')}), ignoring them; download the bundle again to restore them`);
|
|
754
|
+
}
|
|
746
755
|
if (active.length === 0) {
|
|
747
|
-
throw new Error(
|
|
756
|
+
throw new Error(`openManifest: no shards left in ${manifestFile} after include/exclude filtering and dropping absent ones`);
|
|
748
757
|
}
|
|
749
758
|
return { baseDir, manifest: { ...full, shards: active } };
|
|
750
759
|
}
|
|
@@ -797,7 +806,7 @@ class SigDatabaseSet {
|
|
|
797
806
|
if (!ref) {
|
|
798
807
|
throw new Error(`manifest references unknown dictionary '${dictId}'`);
|
|
799
808
|
}
|
|
800
|
-
const plain = (0, decompress_1.ensurePlainSync)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true });
|
|
809
|
+
const plain = (0, decompress_1.ensurePlainSync)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true, bytes: ref.byteCount });
|
|
801
810
|
let strings;
|
|
802
811
|
const fd = fs_1.default.openSync(plain, 'r');
|
|
803
812
|
try {
|
|
@@ -840,10 +849,10 @@ class SigDatabaseSet {
|
|
|
840
849
|
/** decompress the given shards + their shared dictionaries concurrently, then open them (see {@link preload}) */
|
|
841
850
|
async warmShards(need) {
|
|
842
851
|
const dicts = new Set([...need].map(i => this.manifest.shards[i].dict).filter((d) => !!d));
|
|
843
|
-
const shardJobs = [...need].map(i => (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, this.manifest.shards[i].path), { cacheDir: this.cacheDir, hash: this.manifest.shards[i].hash, index: this.indices[i] }));
|
|
852
|
+
const shardJobs = [...need].map(i => (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, this.manifest.shards[i].path), { cacheDir: this.cacheDir, hash: this.manifest.shards[i].hash, index: this.indices[i], bytes: this.indices[i]?.byteCount }));
|
|
844
853
|
const dictJobs = [...dicts].map(id => {
|
|
845
854
|
const ref = this.manifest.dicts?.find(d => d.id === id);
|
|
846
|
-
return ref ? (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true }) : Promise.resolve('');
|
|
855
|
+
return ref ? (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true, bytes: ref.byteCount }) : Promise.resolve('');
|
|
847
856
|
});
|
|
848
857
|
await Promise.all([...shardJobs, ...dictJobs]);
|
|
849
858
|
// open each shard now so later synchronous queries never block
|