Skip to content

Commit 6fb52d2

Browse files
committed
oci: loadArchive to import an index from a tar archive image bundle
Signed-off-by: CrazyMax <[email protected]>
1 parent 2941f52 commit 6fb52d2

24 files changed

+646
-6
lines changed

.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
/.yarn/releases/** binary
22
/.yarn/plugins/** binary
3+
/__tests__/fixtures/oci-archive/** binary

__tests__/fixtures/hello.Dockerfile

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
FROM busybox
17+
FROM busybox AS build
1818
ARG NAME=foo
1919
ARG TARGETPLATFORM
20-
RUN echo "Hello $NAME from $TARGETPLATFORM"
20+
RUN echo "Hello $NAME from $TARGETPLATFORM" > foo
21+
22+
FROM scratch
23+
COPY --from=build /foo /
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

__tests__/oci/oci.test.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Copyright 2024 actions-toolkit authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import {afterEach, beforeEach, describe, expect, jest, test} from '@jest/globals';
18+
import * as fs from 'fs';
19+
import path from 'path';
20+
import * as rimraf from 'rimraf';
21+
22+
import {OCI} from '../../src/oci/oci';
23+
24+
const fixturesDir = path.join(__dirname, '..', 'fixtures');
25+
26+
// prettier-ignore
27+
const tmpDir = path.join(process.env.TEMP || '/tmp', 'docker-jest');
28+
29+
beforeEach(() => {
30+
jest.clearAllMocks();
31+
});
32+
33+
afterEach(function () {
34+
rimraf.sync(tmpDir);
35+
});
36+
37+
describe('loadArchive', () => {
38+
// prettier-ignore
39+
test.each(fs.readdirSync(path.join(fixturesDir, 'oci-archive')).filter(file => {
40+
return fs.statSync(path.join(path.join(fixturesDir, 'oci-archive'), file)).isFile();
41+
}).map(filename => [filename]))('extracting %p', async (filename) => {
42+
const res = await OCI.loadArchive({
43+
file: path.join(fixturesDir, 'oci-archive', filename)
44+
});
45+
expect(res).toBeDefined();
46+
expect(res?.root.index).toBeDefined();
47+
expect(res?.root.layout).toBeDefined();
48+
// console.log(JSON.stringify(res, null, 2));
49+
});
50+
});

package.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,17 +58,21 @@
5858
"@octokit/plugin-rest-endpoint-methods": "^10.4.0",
5959
"async-retry": "^1.3.3",
6060
"csv-parse": "^5.5.6",
61+
"gunzip-maybe": "^1.4.2",
6162
"handlebars": "^4.7.8",
6263
"js-yaml": "^4.1.0",
6364
"jwt-decode": "^4.0.0",
6465
"semver": "^7.6.2",
66+
"tar-stream": "^3.1.7",
6567
"tmp": "^0.2.3"
6668
},
6769
"devDependencies": {
6870
"@types/csv-parse": "^1.2.2",
71+
"@types/gunzip-maybe": "^1.4.2",
6972
"@types/js-yaml": "^4.0.9",
7073
"@types/node": "^20.12.10",
7174
"@types/semver": "^7.5.8",
75+
"@types/tar-stream": "^3.1.3",
7276
"@types/tmp": "^0.2.6",
7377
"@typescript-eslint/eslint-plugin": "^7.8.0",
7478
"@typescript-eslint/parser": "^7.8.0",

src/oci/oci.ts

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
/**
2+
* Copyright 2024 actions-toolkit authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
import fs from 'fs';
17+
import gunzip from 'gunzip-maybe';
18+
import * as path from 'path';
19+
import {Readable} from 'stream';
20+
import * as tar from 'tar-stream';
21+
22+
import {Archive, LoadArchiveOpts} from '../types/oci/oci';
23+
import {Index} from '../types/oci';
24+
import {Manifest} from '../types/oci/manifest';
25+
import {Image} from '../types/oci/config';
26+
import {IMAGE_BLOBS_DIR_V1, IMAGE_INDEX_FILE_V1, IMAGE_LAYOUT_FILE_V1, ImageLayout} from '../types/oci/layout';
27+
import {MEDIATYPE_IMAGE_INDEX_V1, MEDIATYPE_IMAGE_MANIFEST_V1} from '../types/oci/mediatype';
28+
29+
export class OCI {
30+
public static loadArchive(opts: LoadArchiveOpts): Promise<Archive> {
31+
return new Promise<Archive>((resolve, reject) => {
32+
const tarex: tar.Extract = tar.extract();
33+
34+
let rootIndex: Index;
35+
let rootLayout: ImageLayout;
36+
const indexes: Record<string, Index> = {};
37+
const manifests: Record<string, Manifest> = {};
38+
const images: Record<string, Image> = {};
39+
const blobs: Record<string, unknown> = {};
40+
41+
tarex.on('entry', async (header, stream, next) => {
42+
if (header.type === 'file') {
43+
const filename = path.normalize(header.name);
44+
if (filename === IMAGE_INDEX_FILE_V1) {
45+
rootIndex = await OCI.streamToJson<Index>(stream);
46+
} else if (filename === IMAGE_LAYOUT_FILE_V1) {
47+
rootLayout = await OCI.streamToJson<ImageLayout>(stream);
48+
} else if (filename.startsWith(path.join(IMAGE_BLOBS_DIR_V1, path.sep))) {
49+
const blob = await OCI.extractBlob(stream);
50+
const digest = `${filename.split(path.sep)[1]}:${filename.split(path.sep)[filename.split(path.sep).length - 1]}`;
51+
if (OCI.isIndex(blob)) {
52+
indexes[digest] = <Index>JSON.parse(blob);
53+
} else if (OCI.isManifest(blob)) {
54+
manifests[digest] = <Manifest>JSON.parse(blob);
55+
} else if (OCI.isImage(blob)) {
56+
images[digest] = <Image>JSON.parse(blob);
57+
} else {
58+
blobs[digest] = blob;
59+
}
60+
} else {
61+
reject(new Error(`Invalid OCI archive: unexpected file ${filename}`));
62+
}
63+
}
64+
stream.resume();
65+
next();
66+
});
67+
68+
tarex.on('finish', () => {
69+
if (!rootIndex || !rootLayout) {
70+
reject(new Error('Invalid OCI archive: missing index or layout'));
71+
}
72+
resolve({
73+
root: {
74+
index: rootIndex,
75+
layout: rootLayout
76+
},
77+
indexes: indexes,
78+
manifests: manifests,
79+
images: images,
80+
blobs: blobs
81+
} as Archive);
82+
});
83+
84+
tarex.on('error', error => {
85+
reject(error);
86+
});
87+
88+
fs.createReadStream(opts.file).pipe(gunzip()).pipe(tarex);
89+
});
90+
}
91+
92+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
93+
private static isIndex(blob: any): boolean {
94+
try {
95+
const index = <Index>JSON.parse(blob);
96+
return index.mediaType === MEDIATYPE_IMAGE_INDEX_V1;
97+
} catch {
98+
return false;
99+
}
100+
}
101+
102+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
103+
private static isManifest(blob: any): boolean {
104+
try {
105+
const manifest = <Manifest>JSON.parse(blob);
106+
return manifest.mediaType === MEDIATYPE_IMAGE_MANIFEST_V1 && manifest.layers.length > 0;
107+
} catch {
108+
return false;
109+
}
110+
}
111+
112+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
113+
private static isImage(blob: any): boolean {
114+
try {
115+
const image = <Image>JSON.parse(blob);
116+
return image.rootfs.type !== '';
117+
} catch {
118+
return false;
119+
}
120+
}
121+
122+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
123+
private static extractBlob(stream: Readable): Promise<any> {
124+
return new Promise<unknown>((resolve, reject) => {
125+
const chunks: Buffer[] = [];
126+
const dstream = stream.pipe(gunzip());
127+
dstream.on('data', chunk => {
128+
chunks.push(chunk);
129+
});
130+
dstream.on('end', () => {
131+
resolve(Buffer.concat(chunks).toString('utf8'));
132+
});
133+
dstream.on('error', async error => {
134+
reject(error);
135+
});
136+
});
137+
}
138+
139+
private static async streamToJson<T>(stream: Readable): Promise<T> {
140+
return new Promise<T>((resolve, reject) => {
141+
const chunks: string[] = [];
142+
let bytes = 0;
143+
stream.on('data', chunk => {
144+
bytes += chunk.length;
145+
if (bytes <= 2 * 1024 * 1024) {
146+
chunks.push(chunk.toString('utf8'));
147+
} else {
148+
reject(new Error('The data stream exceeds the size limit for JSON parsing.'));
149+
}
150+
});
151+
stream.on('end', () => {
152+
try {
153+
resolve(JSON.parse(chunks.join('')));
154+
} catch (error) {
155+
reject(error);
156+
}
157+
});
158+
stream.on('error', async error => {
159+
reject(error);
160+
});
161+
});
162+
}
163+
}

src/types/oci/config.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Copyright 2024 actions-toolkit authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import {Digest} from './digest';
18+
import {Platform} from './descriptor';
19+
20+
export interface ImageConfig {
21+
User?: string;
22+
ExposedPorts?: Record<string, unknown>;
23+
Env?: string[];
24+
Entrypoint?: string[];
25+
Cmd?: string[];
26+
Volumes?: Record<string, unknown>;
27+
WorkingDir?: string;
28+
Labels?: Record<string, string>;
29+
StopSignal?: string;
30+
ArgsEscaped?: boolean;
31+
}
32+
33+
export interface RootFS {
34+
type: string;
35+
diff_ids: Digest[];
36+
}
37+
38+
export interface History {
39+
created?: string; // assuming RFC 3339 formatted string
40+
created_by?: string;
41+
author?: string;
42+
comment?: string;
43+
empty_layer?: boolean;
44+
}
45+
46+
export interface Image extends Platform {
47+
created?: string; // assuming RFC 3339 formatted string
48+
author?: string;
49+
config?: ImageConfig;
50+
rootfs: RootFS;
51+
history?: History[];
52+
}

src/types/oci/descriptor.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Copyright 2024 actions-toolkit authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import {Digest} from './digest';
18+
19+
import {MEDIATYPE_EMPTY_JSON_V1} from './mediatype';
20+
21+
export interface Descriptor {
22+
mediaType: string;
23+
digest: Digest;
24+
size: number;
25+
urls?: string[];
26+
annotations?: Record<string, string>;
27+
data?: string;
28+
platform?: Platform;
29+
artifactType?: string;
30+
}
31+
32+
export interface Platform {
33+
architecture: string;
34+
os: string;
35+
'os.version'?: string;
36+
'os.features'?: string[];
37+
variant?: string;
38+
}
39+
40+
export const DescriptorEmptyJSON: Descriptor = {
41+
mediaType: MEDIATYPE_EMPTY_JSON_V1,
42+
digest: 'sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a',
43+
size: 2,
44+
data: '{}'
45+
};

src/types/oci/digest.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Copyright 2024 actions-toolkit authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
export type Digest = string;

src/types/oci/index.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Copyright 2024 actions-toolkit authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import {Versioned} from './versioned';
18+
import {Descriptor} from './descriptor';
19+
20+
export interface Index extends Versioned {
21+
mediaType?: string;
22+
artifactType?: string;
23+
manifests: Descriptor[];
24+
subject?: Descriptor;
25+
annotations?: Record<string, string>;
26+
}

0 commit comments

Comments
 (0)