re-integrate toolkit code to main action
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
getRepositoryMetadata,
|
||||
getContainerRegistryURL
|
||||
} from '../src/api-client'
|
||||
|
||||
const url = 'https://registry.example.com'
|
||||
|
||||
let fetchMock: jest.SpyInstance
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = jest.spyOn(global, 'fetch')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fetchMock.mockRestore()
|
||||
})
|
||||
|
||||
describe('getRepositoryMetadata', () => {
|
||||
it('returns repository metadata when the fetch response is ok', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ id: '123', owner: { id: '456' } }))
|
||||
)
|
||||
const result = await getRepositoryMetadata(url, 'repository', 'token')
|
||||
expect(result).toEqual({ repoId: '123', ownerId: '456' })
|
||||
})
|
||||
|
||||
it('throws an error when the fetch errors', async () => {
|
||||
fetchMock.mockRejectedValueOnce(new Error('API is down'))
|
||||
await expect(
|
||||
getRepositoryMetadata(url, 'repository', 'token')
|
||||
).rejects.toThrow('API is down')
|
||||
})
|
||||
|
||||
it('throws an error when the response status is not ok', async () => {
|
||||
fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }))
|
||||
await expect(
|
||||
getRepositoryMetadata(url, 'repository', 'token')
|
||||
).rejects.toThrow(
|
||||
'Failed to fetch repository metadata due to bad status code: 500'
|
||||
)
|
||||
})
|
||||
|
||||
it('throws an error when the response data is in the wrong format', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ wrong: 'format' }))
|
||||
)
|
||||
await expect(
|
||||
getRepositoryMetadata(url, 'repository', 'token')
|
||||
).rejects.toThrow(
|
||||
'Failed to fetch repository metadata: unexpected response format'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getContainerRegistryURL', () => {
|
||||
it('returns container registry URL when the fetch response is ok', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ url: 'https://registry.example.com' }))
|
||||
)
|
||||
const result = await getContainerRegistryURL(url)
|
||||
expect(result).toEqual(new URL('https://registry.example.com'))
|
||||
})
|
||||
|
||||
it('throws an error when the fetch errors', async () => {
|
||||
fetchMock.mockRejectedValueOnce(new Error('API is down'))
|
||||
await expect(getContainerRegistryURL(url)).rejects.toThrow('API is down')
|
||||
})
|
||||
|
||||
it('throws an error when the response status is not ok', async () => {
|
||||
fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }))
|
||||
await expect(getContainerRegistryURL(url)).rejects.toThrow(
|
||||
'Failed to fetch container registry url due to bad status code: 500'
|
||||
)
|
||||
})
|
||||
|
||||
it('throws an error when the response data is in the wrong format', async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ wrong: 'format' }))
|
||||
)
|
||||
await expect(getContainerRegistryURL(url)).rejects.toThrow(
|
||||
'Failed to fetch repository metadata: unexpected response format'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as iaToolkit from '@immutable-actions/toolkit'
|
||||
import * as core from '@actions/core'
|
||||
import * as github from '@actions/github'
|
||||
import * as cfg from '../src/config'
|
||||
import * as apiClient from '../src/api-client'
|
||||
|
||||
let getContainerRegistryURLMock: jest.SpyInstance
|
||||
let getInputMock: jest.SpyInstance
|
||||
@@ -11,7 +11,7 @@ const ghcrUrl = new URL('https://ghcr.io')
|
||||
describe('config.resolvePublishActionOptions', () => {
|
||||
beforeEach(() => {
|
||||
getContainerRegistryURLMock = jest
|
||||
.spyOn(iaToolkit, 'getContainerRegistryURL')
|
||||
.spyOn(apiClient, 'getContainerRegistryURL')
|
||||
.mockImplementation()
|
||||
|
||||
getInputMock = jest.spyOn(core, 'getInput').mockImplementation()
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import * as fsHelper from '../src/fs-helper'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import { execSync } from 'child_process'
|
||||
|
||||
const fileContent = 'This is the content of the file'
|
||||
const tmpFileDir = '/tmp'
|
||||
|
||||
describe('stageActionFiles', () => {
|
||||
let sourceDir: string
|
||||
let stagingDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
sourceDir = fsHelper.createTempDir(tmpFileDir, 'source')
|
||||
fs.mkdirSync(`${sourceDir}/src`)
|
||||
fs.writeFileSync(`${sourceDir}/src/main.js`, fileContent)
|
||||
fs.writeFileSync(`${sourceDir}/src/other.js`, fileContent)
|
||||
|
||||
stagingDir = fsHelper.createTempDir(tmpFileDir, 'staging')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(sourceDir, { recursive: true })
|
||||
fs.rmSync(stagingDir, { recursive: true })
|
||||
})
|
||||
|
||||
it('returns an error if no action.yml file is present', () => {
|
||||
expect(() => fsHelper.stageActionFiles(sourceDir, stagingDir)).toThrow(
|
||||
/^No action.yml or action.yaml file found in source repository/
|
||||
)
|
||||
})
|
||||
|
||||
it('copies all non-hidden files to the staging directory', () => {
|
||||
fs.writeFileSync(`${sourceDir}/action.yml`, fileContent)
|
||||
|
||||
fs.mkdirSync(`${sourceDir}/.git`)
|
||||
fs.writeFileSync(`${sourceDir}/.git/HEAD`, fileContent)
|
||||
|
||||
fs.mkdirSync(`${sourceDir}/.github/workflows`, { recursive: true })
|
||||
fs.writeFileSync(`${sourceDir}/.github/workflows/workflow.yml`, fileContent)
|
||||
|
||||
fsHelper.stageActionFiles(sourceDir, stagingDir)
|
||||
expect(fs.existsSync(`${stagingDir}/action.yml`)).toBe(true)
|
||||
expect(fs.existsSync(`${stagingDir}/src/main.js`)).toBe(true)
|
||||
expect(fs.existsSync(`${stagingDir}/src/other.js`)).toBe(true)
|
||||
|
||||
// Hidden files should not be copied
|
||||
expect(fs.existsSync(`${stagingDir}/.git`)).toBe(false)
|
||||
expect(fs.existsSync(`${stagingDir}/.github`)).toBe(false)
|
||||
})
|
||||
|
||||
it('copies all non-hidden files to the staging directory, even if action.yml is in a subdirectory', () => {
|
||||
fs.mkdirSync(`${sourceDir}/my-sub-action`, { recursive: true })
|
||||
fs.writeFileSync(`${sourceDir}/my-sub-action/action.yml`, fileContent)
|
||||
|
||||
fsHelper.stageActionFiles(sourceDir, stagingDir)
|
||||
expect(fs.existsSync(`${stagingDir}/src/main.js`)).toBe(true)
|
||||
expect(fs.existsSync(`${stagingDir}/src/other.js`)).toBe(true)
|
||||
expect(fs.existsSync(`${stagingDir}/my-sub-action/action.yml`)).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts action.yaml as a valid action file as well as action.yml', () => {
|
||||
fs.writeFileSync(`${sourceDir}/action.yaml`, fileContent)
|
||||
|
||||
fsHelper.stageActionFiles(sourceDir, stagingDir)
|
||||
expect(fs.existsSync(`${stagingDir}/action.yaml`)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createArchives', () => {
|
||||
let stageDir: string
|
||||
let archiveDir: string
|
||||
|
||||
beforeAll(() => {
|
||||
stageDir = fsHelper.createTempDir(tmpFileDir, 'staging')
|
||||
fs.writeFileSync(`${stageDir}/hello.txt`, fileContent)
|
||||
fs.writeFileSync(`${stageDir}/world.txt`, fileContent)
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
archiveDir = fsHelper.createTempDir(tmpFileDir, 'archive')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(archiveDir, { recursive: true })
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
fs.rmSync(stageDir, { recursive: true })
|
||||
})
|
||||
|
||||
it('creates archives', async () => {
|
||||
const { zipFile, tarFile } = await fsHelper.createArchives(
|
||||
stageDir,
|
||||
archiveDir
|
||||
)
|
||||
|
||||
expect(zipFile.path).toEqual(`${archiveDir}/archive.zip`)
|
||||
expect(fs.existsSync(zipFile.path)).toEqual(true)
|
||||
expect(fs.statSync(zipFile.path).size).toBeGreaterThan(0)
|
||||
expect(zipFile.sha256.startsWith('sha256:')).toEqual(true)
|
||||
|
||||
expect(tarFile.path).toEqual(`${archiveDir}/archive.tar.gz`)
|
||||
expect(fs.existsSync(tarFile.path)).toEqual(true)
|
||||
expect(fs.statSync(tarFile.path).size).toBeGreaterThan(0)
|
||||
expect(tarFile.sha256.startsWith('sha256:')).toEqual(true)
|
||||
|
||||
// Validate the hashes by comparing to the output of the system's hashing utility
|
||||
const zipSHA = zipFile.sha256.substring(7) // remove "sha256:" prefix
|
||||
const tarSHA = tarFile.sha256.substring(7) // remove "sha256:" prefix
|
||||
|
||||
// sha256 hash is 64 characters long
|
||||
expect(zipSHA).toHaveLength(64)
|
||||
expect(tarSHA).toHaveLength(64)
|
||||
|
||||
let systemZipHash: string
|
||||
let systemTarHash: string
|
||||
|
||||
if (os.platform() === 'win32') {
|
||||
// Windows
|
||||
systemZipHash = execSync(`CertUtil -hashfile ${zipFile.path} SHA256`)
|
||||
.toString()
|
||||
.split(' ')[1]
|
||||
.trim()
|
||||
systemTarHash = execSync(`CertUtil -hashfile ${tarFile.path} SHA256`)
|
||||
.toString()
|
||||
.split(' ')[1]
|
||||
.trim()
|
||||
} else {
|
||||
// Unix-based systems
|
||||
systemZipHash = execSync(`shasum -a 256 ${zipFile.path}`)
|
||||
.toString()
|
||||
.split(' ')[0]
|
||||
systemTarHash = execSync(`shasum -a 256 ${tarFile.path}`)
|
||||
.toString()
|
||||
.split(' ')[0]
|
||||
}
|
||||
|
||||
expect(zipSHA).toEqual(systemZipHash)
|
||||
expect(tarSHA).toEqual(systemTarHash)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createTempDir', () => {
|
||||
let dirs: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
dirs = []
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs) {
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('creates a temporary directory', () => {
|
||||
const tmpDir = fsHelper.createTempDir(tmpFileDir, 'subdir')
|
||||
|
||||
expect(fs.existsSync(tmpDir)).toEqual(true)
|
||||
expect(fs.statSync(tmpDir).isDirectory()).toEqual(true)
|
||||
})
|
||||
|
||||
it('creates a unique temporary directory', () => {
|
||||
const dir1 = fsHelper.createTempDir(tmpFileDir, 'dir1')
|
||||
dirs.push(dir1)
|
||||
|
||||
const dir2 = fsHelper.createTempDir(tmpFileDir, 'dir2')
|
||||
dirs.push(dir2)
|
||||
|
||||
expect(dir1).not.toEqual(dir2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isDirectory', () => {
|
||||
let dir: string
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fsHelper.createTempDir(tmpFileDir, 'subdir')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
})
|
||||
|
||||
it('returns true if the path is a directory', () => {
|
||||
expect(fsHelper.isDirectory(dir)).toEqual(true)
|
||||
})
|
||||
|
||||
it('returns false if the path is not a directory', () => {
|
||||
const tempFile = `${dir}/file.txt`
|
||||
fs.writeFileSync(tempFile, fileContent)
|
||||
expect(fsHelper.isDirectory(tempFile)).toEqual(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readFileContents', () => {
|
||||
let dir: string
|
||||
|
||||
beforeEach(() => {
|
||||
dir = fsHelper.createTempDir(tmpFileDir, 'subdir')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(dir, { recursive: true })
|
||||
})
|
||||
|
||||
it('reads the contents of a file', () => {
|
||||
const tempFile = `${dir}/file.txt`
|
||||
fs.writeFileSync(tempFile, fileContent)
|
||||
|
||||
expect(fsHelper.readFileContents(tempFile).toString()).toEqual(fileContent)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,501 @@
|
||||
import { publishOCIArtifact } from '../src/ghcr-client'
|
||||
import * as fsHelper from '../src/fs-helper'
|
||||
import * as ociContainer from '../src/oci-container'
|
||||
|
||||
// Mocks
|
||||
let fsReadFileSyncMock: jest.SpyInstance
|
||||
let fetchMock: jest.SpyInstance
|
||||
|
||||
const token = 'test-token'
|
||||
const registry = new URL('https://ghcr.io')
|
||||
const repository = 'test-org/test-repo'
|
||||
const semver = '1.2.3'
|
||||
const genericSha = '1234567890' // We should look at using different shas here to catch bug, but that make location validation harder
|
||||
const zipFile: fsHelper.FileMetadata = {
|
||||
path: `test-repo-${semver}.zip`,
|
||||
size: 123,
|
||||
sha256: genericSha
|
||||
}
|
||||
const tarFile: fsHelper.FileMetadata = {
|
||||
path: `test-repo-${semver}.tar.gz`,
|
||||
size: 456,
|
||||
sha256: genericSha
|
||||
}
|
||||
|
||||
const headMockNoExistingBlobs = (): object => {
|
||||
// Simulate none of the blobs existing currently
|
||||
return {
|
||||
status: 404
|
||||
}
|
||||
}
|
||||
|
||||
const headMockAllExistingBlobs = (): object => {
|
||||
// Simulate all of the blobs existing currently
|
||||
return {
|
||||
status: 200
|
||||
}
|
||||
}
|
||||
|
||||
let count = 0
|
||||
const headMockSomeExistingBlobs = (): object => {
|
||||
count++
|
||||
// report one as existing
|
||||
if (count === 1) {
|
||||
return {
|
||||
status: 200
|
||||
}
|
||||
} else {
|
||||
// report all others are missing
|
||||
return {
|
||||
status: 404
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const headMockFailure = (): object => {
|
||||
return {
|
||||
status: 503
|
||||
}
|
||||
}
|
||||
|
||||
const postMockSuccessfulIniationForAllBlobs = (): object => {
|
||||
// Simulate successful initiation of uploads for all blobs & return location
|
||||
return {
|
||||
status: 202,
|
||||
headers: {
|
||||
get: (header: string) => {
|
||||
if (header === 'location') {
|
||||
return `https://ghcr.io/v2/${repository}/blobs/uploads/${genericSha}`
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const postMockFailure = (): object => {
|
||||
// Simulate failed initiation of uploads
|
||||
return {
|
||||
status: 503
|
||||
}
|
||||
}
|
||||
|
||||
const postMockNoLocationHeader = (): object => {
|
||||
return {
|
||||
status: 202,
|
||||
headers: {
|
||||
get: () => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const putMockSuccessfulBlobUpload = (url: string): object => {
|
||||
// Simulate successful upload of all blobs & then the manifest
|
||||
if (url.includes('manifest')) {
|
||||
return {
|
||||
status: 201,
|
||||
headers: {
|
||||
get: (header: string) => {
|
||||
if (header === 'docker-content-digest') {
|
||||
return '1234567678'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 201
|
||||
}
|
||||
}
|
||||
|
||||
const putMockFailure = (): object => {
|
||||
// Simulate fails upload of all blobs & manifest
|
||||
return {
|
||||
status: 500
|
||||
}
|
||||
}
|
||||
|
||||
const putMockFailureManifestUpload = (url: string): object => {
|
||||
// Simulate unsuccessful upload of all blobs & then the manifest
|
||||
if (url.includes('manifest')) {
|
||||
return {
|
||||
status: 500
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 201
|
||||
}
|
||||
}
|
||||
|
||||
type MethodHandlers = {
|
||||
getMock?: (url: string, options: { method: string }) => object
|
||||
headMock?: (url: string, options: { method: string }) => object
|
||||
postMock?: (url: string, options: { method: string }) => object
|
||||
putMock?: (url: string, options: { method: string }) => object
|
||||
}
|
||||
|
||||
function configureFetchMock(
|
||||
fetchMockInstance: jest.SpyInstance,
|
||||
methodHandlers: MethodHandlers
|
||||
): void {
|
||||
fetchMockInstance.mockImplementation(
|
||||
async (url: string, options: { method: string }) => {
|
||||
validateRequestConfig(url, options)
|
||||
switch (options.method) {
|
||||
case 'GET':
|
||||
return methodHandlers.getMock?.(url, options)
|
||||
case 'HEAD':
|
||||
return methodHandlers.headMock?.(url, options)
|
||||
case 'POST':
|
||||
return methodHandlers.postMock?.(url, options)
|
||||
case 'PUT':
|
||||
return methodHandlers.putMock?.(url, options)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const testManifest: ociContainer.Manifest = {
|
||||
schemaVersion: 2,
|
||||
mediaType: 'application/vnd.oci.image.manifest.v1+json',
|
||||
artifactType: 'application/vnd.oci.image.manifest.v1+json',
|
||||
config: {
|
||||
mediaType: 'application/vnd.oci.empty.v1+json',
|
||||
size: 2,
|
||||
digest:
|
||||
'sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a'
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
mediaType: 'application/vnd.oci.empty.v1+json',
|
||||
size: 2,
|
||||
digest:
|
||||
'sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a'
|
||||
},
|
||||
{
|
||||
mediaType: 'application/vnd.github.actions.package.layer.v1.tar+gzip',
|
||||
size: tarFile.size,
|
||||
digest: `sha256:${tarFile.sha256}`,
|
||||
annotations: {
|
||||
'org.opencontainers.image.title': tarFile.path
|
||||
}
|
||||
},
|
||||
{
|
||||
mediaType: 'application/vnd.github.actions.package.layer.v1.zip',
|
||||
size: zipFile.size,
|
||||
digest: `sha256:${zipFile.sha256}`,
|
||||
annotations: {
|
||||
'org.opencontainers.image.title': zipFile.path
|
||||
}
|
||||
}
|
||||
],
|
||||
annotations: {
|
||||
'org.opencontainers.image.created': '2021-01-01T00:00:00.000Z',
|
||||
'action.tar.gz.digest': tarFile.sha256,
|
||||
'action.zip.digest': zipFile.sha256,
|
||||
'com.github.package.type': 'actions_oci_pkg'
|
||||
}
|
||||
}
|
||||
|
||||
describe('publishOCIArtifact', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
|
||||
fsReadFileSyncMock = jest
|
||||
.spyOn(fsHelper, 'readFileContents')
|
||||
.mockImplementation()
|
||||
|
||||
fetchMock = jest.spyOn(global, 'fetch').mockImplementation()
|
||||
})
|
||||
|
||||
it('publishes layer blobs & then a manifest to the provided registry', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockNoExistingBlobs,
|
||||
postMock: postMockSuccessfulIniationForAllBlobs,
|
||||
putMock: putMockSuccessfulBlobUpload
|
||||
})
|
||||
|
||||
// Simulate successful reading of all the files
|
||||
fsReadFileSyncMock.mockImplementation(() => {
|
||||
return Buffer.from('test')
|
||||
})
|
||||
|
||||
await publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(10)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'HEAD')
|
||||
).toHaveLength(3)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'POST')
|
||||
).toHaveLength(3)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'PUT')
|
||||
).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('skips uploading all layer blobs when they all already exist', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockAllExistingBlobs,
|
||||
postMock: postMockSuccessfulIniationForAllBlobs,
|
||||
putMock: putMockSuccessfulBlobUpload
|
||||
})
|
||||
|
||||
// Simulate successful reading of all the files
|
||||
fsReadFileSyncMock.mockImplementation(() => {
|
||||
return Buffer.from('test')
|
||||
})
|
||||
|
||||
await publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
|
||||
// We should only head all the blobs and then upload the manifest
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'HEAD')
|
||||
).toHaveLength(3)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'POST')
|
||||
).toHaveLength(0)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'PUT')
|
||||
).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('skips uploading layer blobs that already exist', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockSomeExistingBlobs,
|
||||
postMock: postMockSuccessfulIniationForAllBlobs,
|
||||
putMock: putMockSuccessfulBlobUpload
|
||||
})
|
||||
count = 0
|
||||
|
||||
// Simulate successful reading of all the files
|
||||
fsReadFileSyncMock.mockImplementation(() => {
|
||||
return Buffer.from('test')
|
||||
})
|
||||
|
||||
await publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(8)
|
||||
// We should only head all the blobs and then upload the missing blobs and manifest
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'HEAD')
|
||||
).toHaveLength(3)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'POST')
|
||||
).toHaveLength(2)
|
||||
expect(
|
||||
fetchMock.mock.calls.filter(call => call[1].method === 'PUT')
|
||||
).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('throws an error if checking for existing blobs fails', async () => {
|
||||
configureFetchMock(fetchMock, { headMock: headMockFailure })
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
).rejects.toThrow(/^Unexpected response from blob check for layer/)
|
||||
})
|
||||
|
||||
it('throws an error if initiating layer upload fails', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockNoExistingBlobs,
|
||||
postMock: postMockFailure
|
||||
})
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
).rejects.toThrow('Unexpected response from POST upload 503')
|
||||
})
|
||||
|
||||
it('throws an error if the upload endpoint does not return a location', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockNoExistingBlobs,
|
||||
postMock: postMockNoLocationHeader
|
||||
})
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
).rejects.toThrow(/^No location header in response from upload post/)
|
||||
})
|
||||
|
||||
it('throws an error if a layer upload fails', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockNoExistingBlobs,
|
||||
postMock: postMockSuccessfulIniationForAllBlobs,
|
||||
putMock: putMockFailure
|
||||
})
|
||||
|
||||
// Simulate successful reading of all the files
|
||||
fsReadFileSyncMock.mockImplementation(() => {
|
||||
return Buffer.from('test')
|
||||
})
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
).rejects.toThrow(/^Unexpected response from PUT upload 500/)
|
||||
})
|
||||
|
||||
it('throws an error if a manifest upload fails', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockNoExistingBlobs,
|
||||
postMock: postMockSuccessfulIniationForAllBlobs,
|
||||
putMock: putMockFailureManifestUpload
|
||||
})
|
||||
|
||||
// Simulate successful reading of all the files
|
||||
fsReadFileSyncMock.mockImplementation(() => {
|
||||
return Buffer.from('test')
|
||||
})
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
).rejects.toThrow(/^Unexpected response from PUT manifest 500/)
|
||||
})
|
||||
|
||||
it('throws an error if reading one of the files fails', async () => {
|
||||
configureFetchMock(fetchMock, {
|
||||
headMock: headMockNoExistingBlobs,
|
||||
postMock: postMockSuccessfulIniationForAllBlobs,
|
||||
putMock: putMockSuccessfulBlobUpload
|
||||
})
|
||||
|
||||
// Simulate successful reading of all the files
|
||||
fsReadFileSyncMock.mockImplementation(() => {
|
||||
throw new Error('failed to read a file: test')
|
||||
})
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
testManifest
|
||||
)
|
||||
).rejects.toThrow('failed to read a file: test')
|
||||
})
|
||||
|
||||
it('throws an error if one of the layers has the wrong media type', async () => {
|
||||
const modifiedTestManifest = { ...testManifest } // This is _NOT_ a deep clone
|
||||
modifiedTestManifest.layers = cloneLayers(modifiedTestManifest.layers)
|
||||
modifiedTestManifest.layers[0].mediaType = 'application/json'
|
||||
|
||||
// just checking to make sure we are not changing the shared object
|
||||
expect(modifiedTestManifest.layers[0].mediaType).not.toEqual(
|
||||
testManifest.layers[0].mediaType
|
||||
)
|
||||
|
||||
await expect(
|
||||
publishOCIArtifact(
|
||||
token,
|
||||
registry,
|
||||
repository,
|
||||
semver,
|
||||
zipFile,
|
||||
tarFile,
|
||||
modifiedTestManifest
|
||||
)
|
||||
).rejects.toThrow('Unknown media type application/json')
|
||||
})
|
||||
})
|
||||
|
||||
// We expect all fetch calls to have auth headers set
|
||||
// This function verifies that given an request config.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function validateRequestConfig(url: string, config: any): void {
|
||||
// Basic URL checks
|
||||
expect(url).toBeDefined()
|
||||
if (!url.startsWith(registry.toString())) {
|
||||
console.log(`${url} does not start with ${registry}`)
|
||||
}
|
||||
// if these expect fails, run the test again with `-- --silent=false`
|
||||
// the console.log above should give a clue about which URL is failing
|
||||
expect(url.startsWith(registry.toString())).toBeTruthy()
|
||||
|
||||
// Config checks
|
||||
expect(config).toBeDefined()
|
||||
|
||||
expect(config.headers).toBeDefined()
|
||||
if (config.headers) {
|
||||
// Check the auth header is set
|
||||
expect(config.headers.Authorization).toBeDefined()
|
||||
// Check the auth header is the base 64 encoded token
|
||||
expect(config.headers.Authorization).toBe(
|
||||
`Bearer ${Buffer.from(token).toString('base64')}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function cloneLayers(layers: ociContainer.Layer[]): ociContainer.Layer[] {
|
||||
const result: ociContainer.Layer[] = []
|
||||
for (const layer of layers) {
|
||||
result.push({ ...layer }) // this is _NOT_ a deep clone
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -9,8 +9,9 @@
|
||||
import * as core from '@actions/core'
|
||||
import * as attest from '@actions/attest'
|
||||
import * as main from '../src/main'
|
||||
import * as iaToolkit from '@immutable-actions/toolkit'
|
||||
import * as cfg from '../src/config'
|
||||
import * as fsHelper from '../src/fs-helper'
|
||||
import * as ghcr from '../src/ghcr-client'
|
||||
|
||||
const ghcrUrl = new URL('https://ghcr.io')
|
||||
|
||||
@@ -40,18 +41,18 @@ describe('run', () => {
|
||||
|
||||
// FS mocks
|
||||
createTempDirMock = jest
|
||||
.spyOn(iaToolkit, 'createTempDir')
|
||||
.spyOn(fsHelper, 'createTempDir')
|
||||
.mockImplementation()
|
||||
createArchivesMock = jest
|
||||
.spyOn(iaToolkit, 'createArchives')
|
||||
.spyOn(fsHelper, 'createArchives')
|
||||
.mockImplementation()
|
||||
stageActionFilesMock = jest
|
||||
.spyOn(iaToolkit, 'stageActionFiles')
|
||||
.spyOn(fsHelper, 'stageActionFiles')
|
||||
.mockImplementation()
|
||||
|
||||
// GHCR Client mocks
|
||||
publishOCIArtifactMock = jest
|
||||
.spyOn(iaToolkit, 'publishOCIArtifact')
|
||||
.spyOn(ghcr, 'publishOCIArtifact')
|
||||
.mockImplementation()
|
||||
|
||||
// Config mocks
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { createActionPackageManifest } from '../src/oci-container'
|
||||
import { FileMetadata } from '../src/fs-helper'
|
||||
|
||||
describe('createActionPackageManifest', () => {
|
||||
it('creates a manifest containing the provided information', () => {
|
||||
const date = new Date()
|
||||
const repo = 'test-org/test-repo'
|
||||
const sanitizedRepo = 'test-org-test-repo'
|
||||
const version = '1.2.3'
|
||||
const repoId = '123'
|
||||
const ownerId = '456'
|
||||
const sourceCommit = 'abc'
|
||||
const tarFile: FileMetadata = {
|
||||
path: '/test/test/test.tar.gz',
|
||||
sha256: 'tarSha',
|
||||
size: 123
|
||||
}
|
||||
const zipFile: FileMetadata = {
|
||||
path: '/test/test/test.zip',
|
||||
sha256: 'zipSha',
|
||||
size: 456
|
||||
}
|
||||
|
||||
const expectedJSON = `{
|
||||
"schemaVersion": 2,
|
||||
"mediaType": "application/vnd.oci.image.manifest.v1+json",
|
||||
"artifactType": "application/vnd.github.actions.package.v1+json",
|
||||
"config": {
|
||||
"mediaType":"application/vnd.oci.empty.v1+json",
|
||||
"size":2,
|
||||
"digest":"sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
|
||||
},
|
||||
"layers":[
|
||||
{
|
||||
"mediaType":"application/vnd.oci.empty.v1+json",
|
||||
"size":2,
|
||||
"digest":"sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
|
||||
},
|
||||
{
|
||||
"mediaType":"application/vnd.github.actions.package.layer.v1.tar+gzip",
|
||||
"size":${tarFile.size},
|
||||
"digest":"${tarFile.sha256}",
|
||||
"annotations":{
|
||||
"org.opencontainers.image.title":"${sanitizedRepo}_${version}.tar.gz"
|
||||
}
|
||||
},
|
||||
{
|
||||
"mediaType":"application/vnd.github.actions.package.layer.v1.zip",
|
||||
"size":${zipFile.size},
|
||||
"digest":"${zipFile.sha256}",
|
||||
"annotations":{
|
||||
"org.opencontainers.image.title":"${sanitizedRepo}_${version}.zip"
|
||||
}
|
||||
}
|
||||
],
|
||||
"annotations":{
|
||||
"org.opencontainers.image.created":"${date.toISOString()}",
|
||||
"action.tar.gz.digest":"${tarFile.sha256}",
|
||||
"action.zip.digest":"${zipFile.sha256}",
|
||||
"com.github.package.type":"actions_oci_pkg",
|
||||
"com.github.package.version":"1.2.3",
|
||||
"com.github.source.repo.id":"123",
|
||||
"com.github.source.repo.owner.id":"456",
|
||||
"com.github.source.commit":"abc"
|
||||
}
|
||||
}`
|
||||
|
||||
const manifest = createActionPackageManifest(
|
||||
{
|
||||
path: 'test.tar.gz',
|
||||
size: tarFile.size,
|
||||
sha256: tarFile.sha256
|
||||
},
|
||||
{
|
||||
path: 'test.zip',
|
||||
size: zipFile.size,
|
||||
sha256: zipFile.sha256
|
||||
},
|
||||
repo,
|
||||
repoId,
|
||||
ownerId,
|
||||
sourceCommit,
|
||||
version,
|
||||
date
|
||||
)
|
||||
|
||||
const manifestJSON = JSON.stringify(manifest)
|
||||
expect(manifestJSON).toEqual(expectedJSON.replace(/\s/g, ''))
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user