Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/api-v2.authz.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { initApp, loadSpec } from 'src/app'
import getToken from 'src/fixtures/jwt'
import OtomiStack from 'src/otomi-stack'
import request from 'supertest'
import { Git } from './git'
import { getSessionStack } from './middleware'
import * as getValuesSchemaModule from './utils'
import TestAgent from 'supertest/lib/agent'
import { FileStore } from './fileStore/file-store'
import { Git } from './git'
import { getSessionStack } from './middleware'
import { AplKind } from './otomi-models'
import * as getValuesSchemaModule from './utils'

const platformAdminToken = getToken(['platform-admin'])
const teamAdminToken = getToken(['team-admin', 'team-team1'])
Expand Down
2 changes: 1 addition & 1 deletion src/api.authz.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ describe('API authz tests', () => {
const data = {
name: 'demo',
gitService: 'github' as 'gitea' | 'github' | 'gitlab',
repositoryUrl: 'https://github.com/buildpacks/samples',
repositoryUrl: 'github.com/buildpacks/samples',
private: true,
secret: 'demo',
}
Expand Down
4 changes: 2 additions & 2 deletions src/openapi/definitions.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -940,7 +940,7 @@ replicas:
default: 1
repoUrl:
description: Path to a remote git repo without protocol. Will use https to access.
pattern: ^(.+@)*([\w\d\.]+)(:[\d]+){0,1}/*(.*)$
pattern: '^(?:(?:https://)?[A-Za-z0-9.-]+\.[A-Za-z]{2,}|git@[A-Za-z0-9.-]+\.[A-Za-z]{2,}:)/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\.git)?$'
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pattern does not work correctly for git@ SSH urls. The non-capturing group incorrectly ends at git@[...]:, causing the pattern to require a slash / that breaks standard SSH URLs like git@host:owner/repo.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pattern only supports two path segments, while normalizeRepoUrl (and the tests) handles three or more, which may cause issues with GitLab subgroups. (e.g., https://gitlab.example.com/platform/backend/my-repo)

type: string
x-message: a valid git repo URL
example: github.com/example/repo
Expand Down Expand Up @@ -1099,7 +1099,7 @@ svcPredeployed:
url:
pattern: ^https?:\/\/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/=]*)
type: string
example: https://gituhb.com/example
example: https://github.com/example
vaultToken:
title: Token
type: string
Expand Down
38 changes: 36 additions & 2 deletions src/utils/codeRepoUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,45 @@ describe('codeRepoUtils', () => {
expect(result).toEqual('git@github.com:user/repo.git')
})

it('should normalize HTTPS URL', () => {
const result = normalizeRepoUrl('https://github.com/user/repo', false, false)
it('should normalize protocol-less HTTPS URL', () => {
const result = normalizeRepoUrl('github.com/user/repo', false, false)
expect(result).toEqual('https://github.com/user/repo.git')
})

it.each([
'javascript:alert(1)',
'data:text/html,<svg/onload=alert(1)>',
'vbscript:msgbox(1)',
'ftp://github.com/example/repo',
'github.com/example',
'github.com/example/repo<script>',
])('should reject unsafe repository URL: %s', (repoUrl) => {
expect(normalizeRepoUrl(repoUrl, false, false)).toBeNull()
})

it.each([
['https://github.com/example/repo', 'https://github.com/example/repo.git'],
['github.com/example/repo', 'https://github.com/example/repo.git'],
['git@github.com:example/repo.git', 'https://github.com/example/repo.git'],
[
'https://gitlab.example.com/platform/backend/my-repo',
'https://gitlab.example.com/platform/backend/my-repo.git',
],
['gitlab.example.com/platform/backend/my-repo', 'https://gitlab.example.com/platform/backend/my-repo.git'],
[
'git@gitlab.example.com:platform/backend/my-repo.git',
'https://gitlab.example.com/platform/backend/my-repo.git',
],
])('should normalize valid repository URL: %s', (input, expected) => {
expect(normalizeRepoUrl(input, false, false)).toEqual(expected)
})

it('should preserve SSH format for private SSH repositories', () => {
const result = normalizeRepoUrl('git@gitlab.example.com:platform/backend/my-repo.git', true, true)

expect(result).toEqual('git@gitlab.example.com:platform/backend/my-repo.git')
})

it('should return null for invalid URL', () => {
const result = normalizeRepoUrl('invalid-url', false, false)
expect(result).toBeNull()
Expand Down
63 changes: 36 additions & 27 deletions src/utils/codeRepoUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,39 +44,48 @@ export async function getGiteaRepoUrls(adminUsername, adminPassword, orgName, do
}
}

const SAFE_HOST_REGEX = /^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
const SAFE_REPO_PATH_REGEX = /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+$/

export function normalizeRepoUrl(inputUrl: string, isPrivate: boolean, isSSH: boolean): string | null {
try {
let parsedUrl: URL
let owner: string
let repoName: string

const cleanUrl = inputUrl
.trim()
.replace(/\.git$/, '')
.replace(/\/$/, '')
const initMatch = cleanUrl.match(
/^(https?:\/\/(github\.com|gitlab\.com)\/([^/]+)\/([^/]+)|git@(github\.com|gitlab\.com):([^/]+)\/([^/]+))/,
)
const cleanUrl = inputUrl.trim().replace(/\/$/, '')

let hostname: string
let repoPath: string

if (cleanUrl.startsWith('git@')) {
const match = cleanUrl
.replace(/\.git$/, '')
.match(/^git@([A-Za-z0-9.-]+\.[A-Za-z]{2,}):([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)$/)

if (!initMatch) throw new Error('Invalid repository URL.')
if (!match) return null

if (inputUrl.startsWith('git@')) {
const match = inputUrl.match(/^git@([^:]+):([^/]+)\/(.+?)(\.git)?$/)
if (!match) throw new Error('Invalid SSH repository URL.')
const [, hostname, extractedOwner, extractedRepo] = match
owner = extractedOwner
repoName = extractedRepo.endsWith('.git') ? extractedRepo : `${extractedRepo}.git`
parsedUrl = new URL(`https://${hostname}/${owner}/${repoName}`)
hostname = match[1]
repoPath = match[2]
} else {
parsedUrl = new URL(inputUrl)
const segments = parsedUrl.pathname.split('/').filter(Boolean)
if (segments.length < 2) throw new Error('Invalid repository URL: not enough segments.')
owner = segments[0]
repoName = segments[1].endsWith('.git') ? segments[1] : `${segments[1]}.git`
const urlToParse = /^[a-z][a-z0-9+.-]*:/i.test(cleanUrl) ? cleanUrl : `https://${cleanUrl}`

const parsed = new URL(urlToParse)

if (parsed.protocol !== 'https:') return null
if (!SAFE_HOST_REGEX.test(parsed.hostname)) return null

repoPath = parsed.pathname.replace(/\.git$/, '').replace(/^\/|\/$/g, '')

if (!SAFE_REPO_PATH_REGEX.test(repoPath)) return null

hostname = parsed.hostname
}
if (isPrivate && isSSH) return `git@${parsedUrl.hostname}:${owner}/${repoName}`
else return `https://${parsedUrl.hostname}/${owner}/${repoName}`
} catch (error) {

const repoWithGitSuffix = `${repoPath}.git`

if (isPrivate && isSSH) {
return `git@${hostname}:${repoWithGitSuffix}`
}

return `https://${hostname}/${repoWithGitSuffix}`
} catch {
return null
}
}
Expand Down
Loading