-
Notifications
You must be signed in to change notification settings - Fork 243
/
Copy pathcontainerFeaturesConfiguration.ts
1261 lines (1078 loc) · 46.2 KB
/
containerFeaturesConfiguration.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as jsonc from 'jsonc-parser';
import * as path from 'path';
import * as URL from 'url';
import * as tar from 'tar';
import * as crypto from 'crypto';
import * as semver from 'semver';
import * as os from 'os';
import { DevContainerConfig, DevContainerFeature, VSCodeCustomizations } from './configuration';
import { mkdirpLocal, readLocalFile, rmLocal, writeLocalFile, cpDirectoryLocal, isLocalFile } from '../spec-utils/pfs';
import { Log, LogLevel, nullLog } from '../spec-utils/log';
import { request } from '../spec-utils/httpRequest';
import { fetchOCIFeature, tryGetOCIFeatureSet, fetchOCIFeatureManifestIfExistsFromUserIdentifier } from './containerFeaturesOCI';
import { uriToFsPath } from './configurationCommonUtils';
import { CommonParams, ManifestContainer, OCIManifest, OCIRef, getRef, getVersionsStrictSorted } from './containerCollectionsOCI';
import { Lockfile, generateLockfile, readLockfile, writeLockfile } from './lockfile';
import { computeDependsOnInstallationOrder } from './containerFeaturesOrder';
import { logFeatureAdvisories } from './featureAdvisories';
import { getEntPasswdShellCommand } from '../spec-common/commonUtils';
import { ContainerError } from '../spec-common/errors';
// v1
const V1_ASSET_NAME = 'devcontainer-features.tgz';
export const V1_DEVCONTAINER_FEATURES_FILE_NAME = 'devcontainer-features.json';
// v2
export const DEVCONTAINER_FEATURE_FILE_NAME = 'devcontainer-feature.json';
export type Feature = SchemaFeatureBaseProperties & SchemaFeatureLifecycleHooks & DeprecatedSchemaFeatureProperties & InternalFeatureProperties;
export const FEATURES_CONTAINER_TEMP_DEST_FOLDER = '/tmp/dev-container-features';
export interface SchemaFeatureLifecycleHooks {
onCreateCommand?: string | string[];
updateContentCommand?: string | string[];
postCreateCommand?: string | string[];
postStartCommand?: string | string[];
postAttachCommand?: string | string[];
}
// Properties who are members of the schema
export interface SchemaFeatureBaseProperties {
id: string;
version?: string;
name?: string;
description?: string;
documentationURL?: string;
licenseURL?: string;
options?: Record<string, FeatureOption>;
containerEnv?: Record<string, string>;
mounts?: Mount[];
init?: boolean;
privileged?: boolean;
capAdd?: string[];
securityOpt?: string[];
entrypoint?: string;
customizations?: VSCodeCustomizations;
installsAfter?: string[];
deprecated?: boolean;
legacyIds?: string[];
dependsOn?: Record<string, string | boolean | Record<string, string | boolean>>;
}
// Properties that are set programmatically for book-keeping purposes
export interface InternalFeatureProperties {
cachePath?: string;
internalVersion?: string;
consecutiveId?: string;
value: boolean | string | Record<string, boolean | string | undefined>;
currentId?: string;
included: boolean;
}
// Old or deprecated properties maintained for backwards compatibility
export interface DeprecatedSchemaFeatureProperties {
buildArg?: string;
include?: string[];
exclude?: string[];
}
export type FeatureOption = {
type: 'boolean';
default?: boolean;
description?: string;
} | {
type: 'string';
enum?: string[];
default?: string;
description?: string;
} | {
type: 'string';
proposals?: string[];
default?: string;
description?: string;
};
export interface Mount {
type: 'bind' | 'volume';
source?: string;
target: string;
external?: boolean;
}
const normalizedMountKeys: Record<string, string> = {
src: 'source',
destination: 'target',
dst: 'target',
};
export function parseMount(str: string): Mount {
return str.split(',')
.map(s => s.split('='))
.reduce((acc, [key, value]) => ({ ...acc, [(normalizedMountKeys[key] || key)]: value }), {}) as Mount;
}
export type SourceInformation = GithubSourceInformation | DirectTarballSourceInformation | FilePathSourceInformation | OCISourceInformation;
interface BaseSourceInformation {
type: string;
userFeatureId: string; // Dictates how a supporting tool will locate and download a given feature. See https://github.com/devcontainers/spec/blob/main/proposals/devcontainer-features.md#referencing-a-feature
userFeatureIdWithoutVersion?: string;
}
export interface OCISourceInformation extends BaseSourceInformation {
type: 'oci';
featureRef: OCIRef;
manifest: OCIManifest;
manifestDigest: string;
userFeatureIdWithoutVersion: string;
}
export interface DirectTarballSourceInformation extends BaseSourceInformation {
type: 'direct-tarball';
tarballUri: string;
}
export interface FilePathSourceInformation extends BaseSourceInformation {
type: 'file-path';
resolvedFilePath: string; // Resolved, absolute file path
}
// deprecated
export interface GithubSourceInformation extends BaseSourceInformation {
type: 'github-repo';
apiUri: string;
unauthenticatedUri: string;
owner: string;
repo: string;
isLatest: boolean; // 'true' indicates user didn't supply a version tag, thus we implicitly pull latest.
tag?: string;
ref?: string;
sha?: string;
userFeatureIdWithoutVersion: string;
}
export interface FeatureSet {
features: Feature[];
internalVersion?: string;
sourceInformation: SourceInformation;
computedDigest?: string;
}
export interface FeaturesConfig {
featureSets: FeatureSet[];
dstFolder?: string; // set programatically
}
export interface GitHubApiReleaseInfo {
assets: GithubApiReleaseAsset[];
name: string;
tag_name: string;
}
export interface GithubApiReleaseAsset {
url: string;
name: string;
content_type: string;
size: number;
download_count: number;
updated_at: string;
}
export interface ContainerFeatureInternalParams {
extensionPath: string;
cacheFolder: string;
cwd: string;
output: Log;
env: NodeJS.ProcessEnv;
skipFeatureAutoMapping: boolean;
platform: NodeJS.Platform;
experimentalLockfile?: boolean;
experimentalFrozenLockfile?: boolean;
}
// TODO: Move to node layer.
export function getContainerFeaturesBaseDockerFile(contentSourceRootPath: string) {
return `
#{nonBuildKitFeatureContentFallback}
FROM $_DEV_CONTAINERS_BASE_IMAGE AS dev_containers_feature_content_normalize
USER root
COPY --from=dev_containers_feature_content_source ${path.posix.join(contentSourceRootPath, 'devcontainer-features.builtin.env')} /tmp/build-features/
RUN chmod -R 0755 /tmp/build-features/
FROM $_DEV_CONTAINERS_BASE_IMAGE AS dev_containers_target_stage
USER root
RUN mkdir -p ${FEATURES_CONTAINER_TEMP_DEST_FOLDER}
COPY --from=dev_containers_feature_content_normalize /tmp/build-features/ ${FEATURES_CONTAINER_TEMP_DEST_FOLDER}
#{featureLayer}
#{containerEnv}
ARG _DEV_CONTAINERS_IMAGE_USER=root
USER $_DEV_CONTAINERS_IMAGE_USER
#{devcontainerMetadata}
#{containerEnvMetadata}
`;
}
export function getFeatureInstallWrapperScript(feature: Feature, featureSet: FeatureSet, options: string[]): string {
const id = escapeQuotesForShell(featureSet.sourceInformation.userFeatureIdWithoutVersion ?? 'Unknown');
const name = escapeQuotesForShell(feature.name ?? 'Unknown');
const description = escapeQuotesForShell(feature.description ?? '');
const version = escapeQuotesForShell(feature.version ?? '');
const documentation = escapeQuotesForShell(feature.documentationURL ?? '');
const optionsIndented = escapeQuotesForShell(options.map(x => ` ${x}`).join('\n'));
let warningHeader = '';
if (feature.deprecated) {
warningHeader += `(!) WARNING: Using the deprecated Feature "${escapeQuotesForShell(feature.id)}". This Feature will no longer receive any further updates/support.\n`;
}
if (feature?.legacyIds && feature.legacyIds.length > 0 && feature.currentId && feature.id !== feature.currentId) {
warningHeader += `(!) WARNING: This feature has been renamed. Please update the reference in devcontainer.json to "${escapeQuotesForShell(feature.currentId)}".`;
}
const echoWarning = warningHeader ? `echo '${warningHeader}'` : '';
const errorMessage = `ERROR: Feature "${name}" (${id}) failed to install!`;
const troubleshootingMessage = documentation
? ` Look at the documentation at ${documentation} for help troubleshooting this error.`
: '';
return `#!/bin/sh
set -e
on_exit () {
[ $? -eq 0 ] && exit
echo '${errorMessage}${troubleshootingMessage}'
}
trap on_exit EXIT
echo ===========================================================================
${echoWarning}
echo 'Feature : ${name}'
echo 'Description : ${description}'
echo 'Id : ${id}'
echo 'Version : ${version}'
echo 'Documentation : ${documentation}'
echo 'Options :'
echo '${optionsIndented}'
echo ===========================================================================
set -a
. ../devcontainer-features.builtin.env
. ./devcontainer-features.env
set +a
chmod +x ./install.sh
./install.sh
`;
}
function escapeQuotesForShell(input: string) {
// The `input` is expected to be a string which will be printed inside single quotes
// by the caller. This means we need to escape any nested single quotes within the string.
// We can do this by ending the first string with a single quote ('), printing an escaped
// single quote (\'), and then opening a new string (').
return input.replace(new RegExp(`'`, 'g'), `'\\''`);
}
export function getFeatureLayers(featuresConfig: FeaturesConfig, containerUser: string, remoteUser: string, isBuildah = false, useBuildKitBuildContexts = false, contentSourceRootPath = '/tmp/build-features') {
const useSELinuxLabel = process.platform === 'linux' && isBuildah;
const builtinsEnvFile = `${path.posix.join(FEATURES_CONTAINER_TEMP_DEST_FOLDER, 'devcontainer-features.builtin.env')}`;
let result = `RUN \\
echo "_CONTAINER_USER_HOME=$(${getEntPasswdShellCommand(containerUser)} | cut -d: -f6)" >> ${builtinsEnvFile} && \\
echo "_REMOTE_USER_HOME=$(${getEntPasswdShellCommand(remoteUser)} | cut -d: -f6)" >> ${builtinsEnvFile}
`;
// Features version 1
const folders = (featuresConfig.featureSets || []).filter(y => y.internalVersion !== '2').map(x => x.features[0].consecutiveId);
folders.forEach(folder => {
const source = path.posix.join(contentSourceRootPath, folder!);
const dest = path.posix.join(FEATURES_CONTAINER_TEMP_DEST_FOLDER, folder!);
if (!useBuildKitBuildContexts) {
result += `COPY --chown=root:root --from=dev_containers_feature_content_source ${source} ${dest}
RUN chmod -R 0755 ${dest} \\
&& cd ${dest} \\
&& chmod +x ./install.sh \\
&& ./install.sh
`;
} else {
result += `RUN --mount=type=bind,from=dev_containers_feature_content_source,source=${source},target=/tmp/build-features-src/${folder}${useSELinuxLabel ? ',z' : ''} \\
cp -ar /tmp/build-features-src/${folder} ${FEATURES_CONTAINER_TEMP_DEST_FOLDER} \\
&& chmod -R 0755 ${dest} \\
&& cd ${dest} \\
&& chmod +x ./install.sh \\
&& ./install.sh \\
&& rm -rf ${dest}
`;
}
});
// Features version 2
featuresConfig.featureSets.filter(y => y.internalVersion === '2').forEach(featureSet => {
featureSet.features.forEach(feature => {
result += generateContainerEnvs(feature.containerEnv);
const source = path.posix.join(contentSourceRootPath, feature.consecutiveId!);
const dest = path.posix.join(FEATURES_CONTAINER_TEMP_DEST_FOLDER, feature.consecutiveId!);
if (!useBuildKitBuildContexts) {
result += `
COPY --chown=root:root --from=dev_containers_feature_content_source ${source} ${dest}
RUN chmod -R 0755 ${dest} \\
&& cd ${dest} \\
&& chmod +x ./devcontainer-features-install.sh \\
&& ./devcontainer-features-install.sh
`;
} else {
result += `
RUN --mount=type=bind,from=dev_containers_feature_content_source,source=${source},target=/tmp/build-features-src/${feature.consecutiveId}${useSELinuxLabel ? ',z' : ''} \\
cp -ar /tmp/build-features-src/${feature.consecutiveId} ${FEATURES_CONTAINER_TEMP_DEST_FOLDER} \\
&& chmod -R 0755 ${dest} \\
&& cd ${dest} \\
&& chmod +x ./devcontainer-features-install.sh \\
&& ./devcontainer-features-install.sh \\
&& rm -rf ${dest}
`;
}
});
});
return result;
}
// Features version two export their environment variables as part of the Dockerfile to make them available to subsequent features.
export function generateContainerEnvs(containerEnv: Record<string, string> | undefined, escapeDollar = false): string {
if (!containerEnv) {
return '';
}
const keys = Object.keys(containerEnv);
// https://docs.docker.com/engine/reference/builder/#envs
const r = escapeDollar ? /(?=["\\$])/g : /(?=["\\])/g; // escape double quotes, back slash, and optionally dollar sign
return keys.map(k => `ENV ${k}="${containerEnv[k]
.replace(r, '\\')
}"`).join('\n');
}
const allowedFeatureIdRegex = new RegExp('^[a-zA-Z0-9_-]*$');
// Parses a declared feature in user's devcontainer file into
// a usable URI to download remote features.
// RETURNS
// {
// "id", <----- The ID of the feature in the feature set.
// sourceInformation <----- Source information (is this locally cached, a GitHub remote feature, etc..), including tarballUri if applicable.
// }
//
const cleanupIterationFetchAndMerge = async (tempTarballPath: string, output: Log) => {
// Non-fatal, will just get overwritten if we don't do the cleaned up.
try {
await rmLocal(tempTarballPath, { force: true });
} catch (e) {
output.write(`Didn't remove temporary tarball from disk with caught exception: ${e?.Message} `, LogLevel.Trace);
}
};
function getRequestHeaders(params: CommonParams, sourceInformation: SourceInformation) {
const { env, output } = params;
let headers: { 'user-agent': string; 'Authorization'?: string; 'Accept'?: string } = {
'user-agent': 'devcontainer'
};
const isGitHubUri = (srcInfo: DirectTarballSourceInformation) => {
const uri = srcInfo.tarballUri;
return uri.startsWith('https://github.com') || uri.startsWith('https://api.github.com');
};
if (sourceInformation.type === 'github-repo' || (sourceInformation.type === 'direct-tarball' && isGitHubUri(sourceInformation))) {
const githubToken = env['GITHUB_TOKEN'];
if (githubToken) {
output.write('Using environment GITHUB_TOKEN.');
headers.Authorization = `Bearer ${githubToken}`;
} else {
output.write('No environment GITHUB_TOKEN available.');
}
}
return headers;
}
async function askGitHubApiForTarballUri(sourceInformation: GithubSourceInformation, feature: Feature, headers: { 'user-agent': string; 'Authorization'?: string; 'Accept'?: string }, output: Log) {
const options = {
type: 'GET',
url: sourceInformation.apiUri,
headers
};
const apiInfo: GitHubApiReleaseInfo = JSON.parse(((await request(options, output)).toString()));
if (apiInfo) {
const asset =
apiInfo.assets.find(a => a.name === `${feature.id}.tgz`) // v2
|| apiInfo.assets.find(a => a.name === V1_ASSET_NAME) // v1
|| undefined;
if (asset && asset.url) {
output.write(`Found url to fetch release artifact '${asset.name}'. Asset of size ${asset.size} has been downloaded ${asset.download_count} times and was last updated at ${asset.updated_at}`);
return asset.url;
} else {
output.write('Unable to fetch release artifact URI from GitHub API', LogLevel.Error);
return undefined;
}
}
return undefined;
}
function updateFromOldProperties<T extends { features: (Feature & { extensions?: string[]; settings?: object; customizations?: VSCodeCustomizations })[] }>(original: T): T {
// https://github.com/microsoft/dev-container-spec/issues/1
if (!original.features.find(f => f.extensions || f.settings)) {
return original;
}
return {
...original,
features: original.features.map(f => {
if (!(f.extensions || f.settings)) {
return f;
}
const copy = { ...f };
const customizations = copy.customizations || (copy.customizations = {});
const vscode = customizations.vscode || (customizations.vscode = {});
if (copy.extensions) {
vscode.extensions = (vscode.extensions || []).concat(copy.extensions);
delete copy.extensions;
}
if (copy.settings) {
vscode.settings = {
...copy.settings,
...(vscode.settings || {}),
};
delete copy.settings;
}
return copy;
}),
};
}
// Generate a base featuresConfig object with the set of locally-cached features,
// as well as downloading and merging in remote feature definitions.
export async function generateFeaturesConfig(params: ContainerFeatureInternalParams, dstFolder: string, config: DevContainerConfig, additionalFeatures: Record<string, string | boolean | Record<string, string | boolean>>) {
const { output } = params;
const workspaceRoot = params.cwd;
output.write(`workspace root: ${workspaceRoot}`, LogLevel.Trace);
const userFeatures = updateDeprecatedFeaturesIntoOptions(userFeaturesToArray(config, additionalFeatures), output);
if (!userFeatures) {
return undefined;
}
let configPath = config.configFilePath && uriToFsPath(config.configFilePath, params.platform);
output.write(`configPath: ${configPath}`, LogLevel.Trace);
const ociCacheDir = await prepareOCICache(dstFolder);
const { lockfile, initLockfile } = await readLockfile(config);
const processFeature = async (_userFeature: DevContainerFeature) => {
return await processFeatureIdentifier(params, configPath, workspaceRoot, _userFeature, lockfile);
};
output.write('--- Processing User Features ----', LogLevel.Trace);
const featureSets = await computeDependsOnInstallationOrder(params, processFeature, userFeatures, config, lockfile);
if (!featureSets) {
throw new Error('Failed to compute Feature installation order!');
}
// Create the featuresConfig object.
const featuresConfig: FeaturesConfig = {
featureSets,
dstFolder
};
// Fetch features, stage into the appropriate build folder, and read the feature's devcontainer-feature.json
output.write('--- Fetching User Features ----', LogLevel.Trace);
await fetchFeatures(params, featuresConfig, dstFolder, ociCacheDir, lockfile);
await logFeatureAdvisories(params, featuresConfig);
await writeLockfile(params, config, await generateLockfile(featuresConfig), initLockfile);
return featuresConfig;
}
export async function loadVersionInfo(params: ContainerFeatureInternalParams, config: DevContainerConfig) {
const userFeatures = userFeaturesToArray(config);
if (!userFeatures) {
return { features: {} };
}
const { lockfile } = await readLockfile(config);
const resolved: Record<string, any> = {};
await Promise.all(userFeatures.map(async userFeature => {
const userFeatureId = userFeature.userFeatureId;
const featureRef = getRef(nullLog, userFeatureId); // Filters out Feature identifiers that cannot be versioned (e.g. local paths, deprecated, etc..)
if (featureRef) {
const versions = (await getVersionsStrictSorted(params, featureRef))
?.reverse();
if (versions) {
const lockfileVersion = lockfile?.features[userFeatureId]?.version;
let wanted = lockfileVersion;
const tag = featureRef.tag;
if (tag) {
if (tag === 'latest') {
wanted = versions[0];
} else {
wanted = versions.find(version => semver.satisfies(version, tag));
}
} else if (featureRef.digest && !wanted) {
const { type, manifest } = await getFeatureIdType(params, userFeatureId, undefined);
if (type === 'oci' && manifest) {
const wantedFeature = await findOCIFeatureMetadata(params, manifest);
wanted = wantedFeature?.version;
}
}
resolved[userFeatureId] = {
current: lockfileVersion || wanted,
wanted,
wantedMajor: wanted && semver.major(wanted)?.toString(),
latest: versions[0],
latestMajor: semver.major(versions[0])?.toString(),
};
}
}
}));
// Reorder Features to match the order in which they were specified in config
return {
features: userFeatures.reduce((acc, userFeature) => {
const r = resolved[userFeature.userFeatureId];
if (r) {
acc[userFeature.userFeatureId] = r;
}
return acc;
}, {} as Record<string, any>)
};
}
async function findOCIFeatureMetadata(params: ContainerFeatureInternalParams, manifest: ManifestContainer) {
const annotation = manifest.manifestObj.annotations?.['dev.containers.metadata'];
if (annotation) {
return jsonc.parse(annotation) as Feature;
}
// Backwards compatibility.
const featureSet = tryGetOCIFeatureSet(params.output, manifest.canonicalId, {}, manifest, manifest.canonicalId);
if (!featureSet) {
return undefined;
}
const tmp = path.join(os.tmpdir(), crypto.randomUUID());
const f = await fetchOCIFeature(params, featureSet, tmp, tmp, DEVCONTAINER_FEATURE_FILE_NAME);
return f.metadata as Feature | undefined;
}
async function prepareOCICache(dstFolder: string) {
const ociCacheDir = path.join(dstFolder, 'ociCache');
await mkdirpLocal(ociCacheDir);
return ociCacheDir;
}
export function userFeaturesToArray(config: DevContainerConfig, additionalFeatures?: Record<string, string | boolean | Record<string, string | boolean>>): DevContainerFeature[] | undefined {
if (!Object.keys(config.features || {}).length && !Object.keys(additionalFeatures || {}).length) {
return undefined;
}
const userFeatures: DevContainerFeature[] = [];
const userFeatureKeys = new Set<string>();
if (config.features) {
for (const userFeatureKey of Object.keys(config.features)) {
const userFeatureValue = config.features[userFeatureKey];
const feature: DevContainerFeature = {
userFeatureId: userFeatureKey,
options: userFeatureValue
};
userFeatures.push(feature);
userFeatureKeys.add(userFeatureKey);
}
}
if (additionalFeatures) {
for (const userFeatureKey of Object.keys(additionalFeatures)) {
// add the additional feature if it hasn't already been added from the config features
if (!userFeatureKeys.has(userFeatureKey)) {
const userFeatureValue = additionalFeatures[userFeatureKey];
const feature: DevContainerFeature = {
userFeatureId: userFeatureKey,
options: userFeatureValue
};
userFeatures.push(feature);
}
}
}
return userFeatures;
}
const deprecatedFeaturesIntoOptions: Record<string, { mapTo: string; withOptions: any }> = {
gradle: {
mapTo: 'java',
withOptions: {
installGradle: true
}
},
maven: {
mapTo: 'java',
withOptions: {
installMaven: true
}
},
jupyterlab: {
mapTo: 'python',
withOptions: {
installJupyterlab: true
}
},
};
export function updateDeprecatedFeaturesIntoOptions(userFeatures: DevContainerFeature[] | undefined, output: Log) {
if (!userFeatures) {
output.write('No user features to update', LogLevel.Trace);
return;
}
const newFeaturePath = 'ghcr.io/devcontainers/features';
const versionBackwardComp = '1';
for (const update of userFeatures.filter(feature => deprecatedFeaturesIntoOptions[feature.userFeatureId])) {
const { mapTo, withOptions } = deprecatedFeaturesIntoOptions[update.userFeatureId];
output.write(`(!) WARNING: Using the deprecated '${update.userFeatureId}' Feature. It is now part of the '${mapTo}' Feature. See https://github.com/devcontainers/features/tree/main/src/${mapTo}#options for the updated Feature.`, LogLevel.Warning);
const qualifiedMapToId = `${newFeaturePath}/${mapTo}`;
let userFeature = userFeatures.find(feature => feature.userFeatureId === mapTo || feature.userFeatureId === qualifiedMapToId || feature.userFeatureId.startsWith(`${qualifiedMapToId}:`));
if (userFeature) {
userFeature.options = {
...(
typeof userFeature.options === 'object' ? userFeature.options :
typeof userFeature.options === 'string' ? { version: userFeature.options } :
{}
),
...withOptions,
};
} else {
userFeature = {
userFeatureId: `${qualifiedMapToId}:${versionBackwardComp}`,
options: withOptions
};
userFeatures.push(userFeature);
}
}
const updatedUserFeatures = userFeatures.filter(feature => !deprecatedFeaturesIntoOptions[feature.userFeatureId]);
return updatedUserFeatures;
}
export async function getFeatureIdType(params: CommonParams, userFeatureId: string, lockfile: Lockfile | undefined) {
const { output } = params;
// See the specification for valid feature identifiers:
// > https://github.com/devcontainers/spec/blob/main/proposals/devcontainer-features.md#referencing-a-feature
//
// Additionally, we support the following deprecated syntaxes for backwards compatibility:
// (0) A 'local feature' packaged with the CLI.
// Syntax: <feature>
//
// (1) A feature backed by a GitHub Release
// Syntax: <repoOwner>/<repoName>/<featureId>[@version]
// Legacy feature-set ID
if (!userFeatureId.includes('/') && !userFeatureId.includes('\\')) {
const errorMessage = `Legacy feature '${userFeatureId}' not supported. Please check https://containers.dev/features for replacements.
If you were hoping to use local Features, remember to prepend your Feature name with "./". Please check https://containers.dev/implementors/features-distribution/#addendum-locally-referenced for more information.`;
output.write(errorMessage, LogLevel.Error);
throw new ContainerError({
description: errorMessage
});
}
// Direct tarball reference
if (userFeatureId.startsWith('https://')) {
return { type: 'direct-tarball', manifest: undefined };
}
// Local feature on disk
// !! NOTE: The ability for paths outside the project file tree will soon be removed.
if (userFeatureId.startsWith('./') || userFeatureId.startsWith('../') || userFeatureId.startsWith('/')) {
return { type: 'file-path', manifest: undefined };
}
const manifest = await fetchOCIFeatureManifestIfExistsFromUserIdentifier(params, userFeatureId, lockfile?.features[userFeatureId]?.integrity);
if (manifest) {
return { type: 'oci', manifest: manifest };
} else {
output.write(`Could not resolve Feature manifest for '${userFeatureId}'. If necessary, provide registry credentials with 'docker login <registry>'.`, LogLevel.Warning);
output.write(`Falling back to legacy GitHub Releases mode to acquire Feature.`, LogLevel.Trace);
// DEPRECATED: This is a legacy feature-set ID
return { type: 'github-repo', manifest: undefined };
}
}
export function getBackwardCompatibleFeatureId(output: Log, id: string) {
const migratedfeatures = ['aws-cli', 'azure-cli', 'desktop-lite', 'docker-in-docker', 'docker-from-docker', 'dotnet', 'git', 'git-lfs', 'github-cli', 'java', 'kubectl-helm-minikube', 'node', 'powershell', 'python', 'ruby', 'rust', 'sshd', 'terraform'];
const renamedFeatures = new Map();
renamedFeatures.set('golang', 'go');
renamedFeatures.set('common', 'common-utils');
const deprecatedFeaturesIntoOptions = new Map();
deprecatedFeaturesIntoOptions.set('gradle', 'java');
deprecatedFeaturesIntoOptions.set('maven', 'java');
deprecatedFeaturesIntoOptions.set('jupyterlab', 'python');
const newFeaturePath = 'ghcr.io/devcontainers/features';
// Note: Pin the versionBackwardComp to '1' to avoid breaking changes.
const versionBackwardComp = '1';
// Mapping feature references (old shorthand syntax) from "microsoft/vscode-dev-containers" to "ghcr.io/devcontainers/features"
if (migratedfeatures.includes(id)) {
output.write(`(!) WARNING: Using the deprecated '${id}' Feature. See https://github.com/devcontainers/features/tree/main/src/${id}#example-usage for the updated Feature.`, LogLevel.Warning);
return `${newFeaturePath}/${id}:${versionBackwardComp}`;
}
// Mapping feature references (renamed old shorthand syntax) from "microsoft/vscode-dev-containers" to "ghcr.io/devcontainers/features"
if (renamedFeatures.get(id) !== undefined) {
output.write(`(!) WARNING: Using the deprecated '${id}' Feature. See https://github.com/devcontainers/features/tree/main/src/${renamedFeatures.get(id)}#example-usage for the updated Feature.`, LogLevel.Warning);
return `${newFeaturePath}/${renamedFeatures.get(id)}:${versionBackwardComp}`;
}
if (deprecatedFeaturesIntoOptions.get(id) !== undefined) {
output.write(`(!) WARNING: Falling back to the deprecated '${id}' Feature. It is now part of the '${deprecatedFeaturesIntoOptions.get(id)}' Feature. See https://github.com/devcontainers/features/tree/main/src/${deprecatedFeaturesIntoOptions.get(id)}#options for the updated Feature.`, LogLevel.Warning);
}
// Deprecated and all other features references (eg. fish, ghcr.io/devcontainers/features/go, ghcr.io/owner/repo/id etc)
return id;
}
// Strictly processes the user provided feature identifier to determine sourceInformation type.
// Returns a featureSet per feature.
export async function processFeatureIdentifier(params: CommonParams, configPath: string | undefined, _workspaceRoot: string, userFeature: DevContainerFeature, lockfile?: Lockfile, skipFeatureAutoMapping?: boolean): Promise<FeatureSet | undefined> {
const { output } = params;
output.write(`* Processing feature: ${userFeature.userFeatureId}`);
// id referenced by the user before the automapping from old shorthand syntax to "ghcr.io/devcontainers/features"
const originalUserFeatureId = userFeature.userFeatureId;
// Adding backward compatibility
if (!skipFeatureAutoMapping) {
userFeature.userFeatureId = getBackwardCompatibleFeatureId(output, userFeature.userFeatureId);
}
const { type, manifest } = await getFeatureIdType(params, userFeature.userFeatureId, lockfile);
// remote tar file
if (type === 'direct-tarball') {
output.write(`Remote tar file found.`);
const tarballUri = new URL.URL(userFeature.userFeatureId);
const fullPath = tarballUri.pathname;
const tarballName = fullPath.substring(fullPath.lastIndexOf('/') + 1);
output.write(`tarballName = ${tarballName}`, LogLevel.Trace);
const regex = new RegExp('devcontainer-feature-(.*).tgz');
const matches = regex.exec(tarballName);
if (!matches || matches.length !== 2) {
output.write(`Expected tarball name to follow 'devcontainer-feature-<feature-id>.tgz' format. Received '${tarballName}'`, LogLevel.Error);
return undefined;
}
const id = matches[1];
if (id === '' || !allowedFeatureIdRegex.test(id)) {
output.write(`Parse error. Specify a feature id with alphanumeric, dash, or underscore characters. Received ${id}.`, LogLevel.Error);
return undefined;
}
let feat: Feature = {
id: id,
name: userFeature.userFeatureId,
value: userFeature.options,
included: true,
};
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'direct-tarball',
tarballUri: tarballUri.toString(),
userFeatureId: originalUserFeatureId
},
features: [feat],
};
return newFeaturesSet;
}
// Spec: https://containers.dev/implementors/features-distribution/#addendum-locally-referenced
if (type === 'file-path') {
output.write(`Local disk feature.`);
const id = path.basename(userFeature.userFeatureId);
// Fail on Absolute paths.
if (path.isAbsolute(userFeature.userFeatureId)) {
output.write('An Absolute path to a local feature is not allowed.', LogLevel.Error);
return undefined;
}
// Local-path features are expected to be a sub-folder of the '$WORKSPACE_ROOT/.devcontainer' folder.
if (!configPath) {
output.write('A local feature requires a configuration path.', LogLevel.Error);
return undefined;
}
const featureFolderPath = path.join(path.dirname(configPath), userFeature.userFeatureId);
// Ensure we aren't escaping .devcontainer folder
const parent = path.join(_workspaceRoot, '.devcontainer');
const child = featureFolderPath;
const relative = path.relative(parent, child);
output.write(`${parent} -> ${child}: Relative Distance = '${relative}'`, LogLevel.Trace);
if (relative.indexOf('..') !== -1) {
output.write(`Local file path parse error. Resolved path must be a child of the .devcontainer/ folder. Parsed: ${featureFolderPath}`, LogLevel.Error);
return undefined;
}
output.write(`Resolved: ${userFeature.userFeatureId} -> ${featureFolderPath}`, LogLevel.Trace);
// -- All parsing and validation steps complete at this point.
output.write(`Parsed feature id: ${id}`, LogLevel.Trace);
let feat: Feature = {
id,
name: userFeature.userFeatureId,
value: userFeature.options,
included: true,
};
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'file-path',
resolvedFilePath: featureFolderPath,
userFeatureId: originalUserFeatureId
},
features: [feat],
};
return newFeaturesSet;
}
// (6) Oci Identifier
if (type === 'oci' && manifest) {
return tryGetOCIFeatureSet(output, userFeature.userFeatureId, userFeature.options, manifest, originalUserFeatureId);
}
output.write(`Github feature.`);
// Github repository source.
let version = 'latest';
let splitOnAt = userFeature.userFeatureId.split('@');
if (splitOnAt.length > 2) {
output.write(`Parse error. Use the '@' symbol only to designate a version tag.`, LogLevel.Error);
return undefined;
}
if (splitOnAt.length === 2) {
output.write(`[${userFeature.userFeatureId}] has version ${splitOnAt[1]}`, LogLevel.Trace);
version = splitOnAt[1];
}
// Remaining info must be in the first part of the split.
const featureBlob = splitOnAt[0];
const splitOnSlash = featureBlob.split('/');
// We expect all GitHub/registry features to follow the triple slash pattern at this point
// eg: <publisher>/<feature-set>/<feature>
if (splitOnSlash.length !== 3 || splitOnSlash.some(x => x === '') || !allowedFeatureIdRegex.test(splitOnSlash[2])) {
// This is the final fallback. If we end up here, we weren't able to resolve the Feature
output.write(`Could not resolve Feature '${userFeature.userFeatureId}'. Ensure the Feature is published and accessible from your current environment.`, LogLevel.Error);
return undefined;
}
const owner = splitOnSlash[0];
const repo = splitOnSlash[1];
const id = splitOnSlash[2];
let feat: Feature = {
id: id,
name: userFeature.userFeatureId,
value: userFeature.options,
included: true,
};
const userFeatureIdWithoutVersion = originalUserFeatureId.split('@')[0];
if (version === 'latest') {
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'github-repo',
apiUri: `https://api.github.com/repos/${owner}/${repo}/releases/latest`,
unauthenticatedUri: `https://github.com/${owner}/${repo}/releases/latest/download`, // v1/v2 implementations append name of relevant asset
owner,
repo,
isLatest: true,
userFeatureId: originalUserFeatureId,
userFeatureIdWithoutVersion
},
features: [feat],
};
return newFeaturesSet;
} else {
// We must have a tag, return a tarball URI for the tagged version.
let newFeaturesSet: FeatureSet = {
sourceInformation: {
type: 'github-repo',
apiUri: `https://api.github.com/repos/${owner}/${repo}/releases/tags/${version}`,
unauthenticatedUri: `https://github.com/${owner}/${repo}/releases/download/${version}`, // v1/v2 implementations append name of relevant asset
owner,
repo,
tag: version,
isLatest: false,
userFeatureId: originalUserFeatureId,
userFeatureIdWithoutVersion
},
features: [feat],
};
return newFeaturesSet;
}
// TODO: Handle invalid source types better by refactoring this function.
// throw new Error(`Unsupported feature source type: ${type}`);
}
async function fetchFeatures(params: { extensionPath: string; cwd: string; output: Log; env: NodeJS.ProcessEnv }, featuresConfig: FeaturesConfig, dstFolder: string, ociCacheDir: string, lockfile: Lockfile | undefined) {
const featureSets = featuresConfig.featureSets;
for (let idx = 0; idx < featureSets.length; idx++) { // Index represents the previously computed installation order.
const featureSet = featureSets[idx];
try {
if (!featureSet || !featureSet.features || !featureSet.sourceInformation) {
continue;
}
const { output } = params;
const feature = featureSet.features[0];
const consecutiveId = `${feature.id}_${idx}`;
// Calculate some predictable caching paths.
const featCachePath = path.join(dstFolder, consecutiveId);
const sourceInfoType = featureSet.sourceInformation?.type;
feature.cachePath = featCachePath;
feature.consecutiveId = consecutiveId;
if (!feature.consecutiveId || !feature.id || !featureSet?.sourceInformation || !featureSet.sourceInformation.userFeatureId) {
const err = 'Internal Features error. Missing required attribute(s).';
throw new Error(err);
}
const featureDebugId = `${feature.consecutiveId}_${sourceInfoType}`;
output.write(`* Fetching feature: ${featureDebugId}`);
if (sourceInfoType === 'oci') {
output.write(`Fetching from OCI`, LogLevel.Trace);
await mkdirpLocal(featCachePath);
const res = await fetchOCIFeature(params, featureSet, ociCacheDir, featCachePath);
if (!res) {
const err = `Could not download OCI feature: ${featureSet.sourceInformation.featureRef.id}`;
throw new Error(err);
}
if (!(await applyFeatureConfigToFeature(output, featureSet, feature, featCachePath, featureSet.sourceInformation.manifestDigest))) {
const err = `Failed to parse feature '${featureDebugId}'. Please check your devcontainer.json 'features' attribute.`;
throw new Error(err);
}
output.write(`* Fetched feature: ${featureDebugId} version ${feature.version}`);
continue;
}