@red-hat-developer-hub/backstage-plugin-bulk-import-backend 8.0.3 → 9.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +27 -4
- package/dist/github/githubApiService.cjs.js +17 -0
- package/dist/github/githubApiService.cjs.js.map +1 -1
- package/dist/service/handlers/import/bulkImports.cjs.js +5 -1
- package/dist/service/handlers/import/bulkImports.cjs.js.map +1 -1
- package/dist/service/handlers/import/execute-orchestrator-workflow.cjs.js +8 -2
- package/dist/service/handlers/import/execute-orchestrator-workflow.cjs.js.map +1 -1
- package/dist/service/router.cjs.js +13 -17
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +12 -12
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @red-hat-developer-hub/backstage-plugin-bulk-import-backend
|
|
2
2
|
|
|
3
|
+
## 9.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- df4bcba: Backstage version bump to v1.54.6
|
|
8
|
+
- Updated dependencies [df4bcba]
|
|
9
|
+
- @red-hat-developer-hub/backstage-plugin-bulk-import-common@9.0.1
|
|
10
|
+
|
|
11
|
+
## 9.0.0
|
|
12
|
+
|
|
13
|
+
### Major Changes
|
|
14
|
+
|
|
15
|
+
- b9198f8: Orchestrator import mode now requires short-lived GitHub App installation tokens for `authTokens` and fails closed when only a classic PAT is available. Plugin-to-plugin calls to Orchestrator now use `auth.getPluginRequestToken` instead of forwarding the incoming user bearer token. Operator docs cover App setup, token TTL limits for long-running workflows, GitLab residual risk, RBAC, and deployment hardening.
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- @red-hat-developer-hub/backstage-plugin-bulk-import-common@9.0.0
|
|
20
|
+
|
|
3
21
|
## 8.0.3
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -221,16 +221,20 @@ When executing an orchestrator workflow, the Bulk Import plugin provides the fol
|
|
|
221
221
|
Additionally, the plugin automatically provides authentication tokens for the Git provider:
|
|
222
222
|
|
|
223
223
|
- **`authTokens`** – Array of authentication tokens for the Git provider:
|
|
224
|
-
- For GitHub repositories (`approvalTool: 'GIT'`): `{ token: <github-token>, provider: 'github' }`
|
|
224
|
+
- For GitHub repositories (`approvalTool: 'GIT'`): `{ token: <github-app-installation-token>, provider: 'github' }`
|
|
225
225
|
- For GitLab repositories (`approvalTool: 'GITLAB'`): `{ token: <gitlab-token>, provider: 'gitlab' }`
|
|
226
226
|
|
|
227
|
-
|
|
227
|
+
**GitHub (required for orchestrator mode):** tokens are short-lived **GitHub App installation tokens** from `integrations.github`. The target org/user must have the App installed. Classic personal access tokens (PATs) are **not** forwarded; if only a PAT is configured (or no App installation covers the repo), the import job for that repository fails closed with an error.
|
|
228
|
+
|
|
229
|
+
**GitLab:** tokens still come from `integrations.gitlab` (typically long-lived). There is no short-lived App-equivalent path in this plugin today — residual risk is higher; use least-privilege tokens and keep SonataFlow private until a short-lived approach exists.
|
|
230
|
+
|
|
231
|
+
**Token TTL vs long-running workflows:** GitHub App installation tokens typically expire in about an hour. Credentials are resolved once when the workflow is started and passed into SonataFlow; SonataFlow does **not** re-fetch or refresh them after wait states or long-running steps. Workflows that exceed token lifetime (or wait longer than the TTL) can fail mid-run. Keep orchestrator import workflows short relative to the token TTL, or accept that long/waiting runs may need a retrigger with fresh credentials.
|
|
228
232
|
|
|
229
233
|
##### How Orchestrator Mode Works
|
|
230
234
|
|
|
231
235
|
1. **Workflow Execution**: When you submit a bulk import request with `importAPI: 'orchestrator'`, the plugin:
|
|
232
236
|
- Iterates through each repository in the request
|
|
233
|
-
- Retrieves the appropriate Git provider credentials (GitHub or GitLab)
|
|
237
|
+
- Retrieves the appropriate Git provider credentials (GitHub App installation token, or GitLab integration token)
|
|
234
238
|
- Executes the specified orchestrator workflow for each repository
|
|
235
239
|
- Passes the repository information and authentication tokens as input data
|
|
236
240
|
|
|
@@ -266,7 +270,7 @@ Your orchestrator workflow should accept the input parameters described above. H
|
|
|
266
270
|
},
|
|
267
271
|
"authTokens": [
|
|
268
272
|
{
|
|
269
|
-
"token": "<github-token>",
|
|
273
|
+
"token": "<github-app-installation-token>",
|
|
270
274
|
"provider": "github"
|
|
271
275
|
}
|
|
272
276
|
]
|
|
@@ -292,6 +296,25 @@ The plugin maps Orchestrator workflow states to Bulk Import status values:
|
|
|
292
296
|
|
|
293
297
|
If workflow status cannot be retrieved, the status is set to `WORKFLOW_FETCH_FAILED`.
|
|
294
298
|
|
|
299
|
+
##### RBAC and deployment guidance (orchestrator mode)
|
|
300
|
+
|
|
301
|
+
Because SCM credentials enter the SonataFlow trust boundary for the duration of the workflow, treat access and runtime hardening as part of the control plane:
|
|
302
|
+
|
|
303
|
+
**RBAC (recommended in production):**
|
|
304
|
+
|
|
305
|
+
- Enable the Backstage permission framework.
|
|
306
|
+
- Limit who has `bulk.import`.
|
|
307
|
+
- Scope `orchestrator.workflow.use` (and optional workflow-ID conditions such as `IS_ALLOWED_WORKFLOW_ID`) to the allowlisted workflow configured in `bulkImport.orchestratorWorkflow`.
|
|
308
|
+
- Control who can change that config and who can deploy the workflow definition.
|
|
309
|
+
|
|
310
|
+
**Deployment checklist:**
|
|
311
|
+
|
|
312
|
+
- Keep SonataFlow private (cluster RBAC; no untrusted co-tenants; not exposed to the public internet).
|
|
313
|
+
- Egress-allowlist SonataFlow to SCM and required APIs only.
|
|
314
|
+
- Verify audit, APM, and ingress logging do not persist `authTokens` body values or `X-Authorization-*` header values.
|
|
315
|
+
- Configure the GitHub App with least privilege (for example contents + pull requests on required orgs/repos only).
|
|
316
|
+
- Monitor Bulk Import / Orchestrator audit events and SCM audit for the App identity; maintain a documented revoke/rotate runbook.
|
|
317
|
+
|
|
295
318
|
### Audit Logging
|
|
296
319
|
|
|
297
320
|
Audit logging is backed by the [`@backstage/backend-plugin-api`](https://www.npmjs.com/package/@backstage/backend-plugin-api) package.
|
|
@@ -63,6 +63,23 @@ class GithubApiService {
|
|
|
63
63
|
if (!creds || !creds.token) {
|
|
64
64
|
throw new Error(`Token not configured for 'github' provider`);
|
|
65
65
|
}
|
|
66
|
+
return {
|
|
67
|
+
token: creds.token,
|
|
68
|
+
type: creds.type
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Returns a short-lived GitHub App installation token for the given repo URL.
|
|
73
|
+
* Fails closed if only a classic PAT is available or no App installation exists.
|
|
74
|
+
* Used by orchestrator import mode so long-lived PATs are never forwarded to SonataFlow.
|
|
75
|
+
*/
|
|
76
|
+
async getAppInstallationCredentials(repoUrl) {
|
|
77
|
+
const creds = await this.getCredentials(repoUrl);
|
|
78
|
+
if (creds.type !== "app") {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`Orchestrator import requires a GitHub App installation token for '${repoUrl}'. Configure integrations.github with an App that has access to this repository; classic personal access tokens are not forwarded in orchestrator mode.`
|
|
81
|
+
);
|
|
82
|
+
}
|
|
66
83
|
return {
|
|
67
84
|
token: creds.token
|
|
68
85
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"githubApiService.cjs.js","sources":["../../src/github/githubApiService.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentials,\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName, getCatalogFilename } from '../catalog/catalogUtils';\nimport {\n computeTotalCount,\n extractLocationOwnerMap,\n logErrorIfNeeded,\n} from '../helpers';\nimport { GitApiService } from '../scm/GitApiService';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../service/handlers/handlers';\nimport { CustomGithubCredentialsProvider } from './GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n type GithubOrganization,\n type GithubOrganizationResponse,\n type GithubRepository,\n type GithubRepositoryResponse,\n} from './types';\nimport { buildOcto } from './utils/ghUtils';\nimport {\n addGithubAppOrgs,\n addGithubTokenOrgs,\n getAllAppOrgs,\n} from './utils/orgUtils';\nimport {\n closePRWithComment,\n findOpenPRForBranch,\n getCatalogInfoContentFromPR,\n} from './utils/prUtils';\nimport {\n addGithubAppRepositories,\n addGithubTokenOrgRepositories,\n addGithubTokenRepositories,\n fileExistsInDefaultBranch,\n type ValidatedRepo,\n} from './utils/repoUtils';\nimport {\n executeFunctionOnFirstSuccessfulIntegration,\n fetchFromAllIntegrations,\n fetchFromMatchedIntegration,\n} from './utils/utils';\n\nexport class GithubApiService implements GitApiService {\n private readonly logger: LoggerService;\n private readonly integrations: ScmIntegrations;\n public readonly githubCredentialsProvider: CustomGithubCredentialsProvider;\n private readonly config: Config;\n // Cache for storing ETags (used for efficient caching of unchanged data returned by GitHub)\n private readonly cache: CacheService;\n\n constructor(\n logger: LoggerService,\n config: Config,\n cacheService: CacheService,\n ) {\n this.logger = logger;\n this.config = config;\n this.integrations = ScmIntegrations.fromConfig(config);\n this.githubCredentialsProvider =\n CustomGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.cache = cacheService;\n }\n\n private get integrationDeps() {\n return {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n };\n }\n\n private get executionDeps() {\n return {\n ...this.integrationDeps,\n config: this.config,\n };\n }\n\n private buildRepositoryResponse(\n repositories: Map<string, GithubRepository>,\n result: { data: number[]; errors: Map<number, GithubFetchError> },\n pageSize: number,\n ): GithubRepositoryResponse {\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors.values()),\n totalCount,\n };\n }\n\n async getCredentials(repoUrl: string): Promise<{ token: string }> {\n const provider = DefaultGithubCredentialsProvider.fromIntegrations(\n this.integrations,\n );\n const creds = await provider.getCredentials({\n url: repoUrl,\n });\n if (!creds || !creds.token) {\n throw new Error(`Token not configured for 'github' provider`);\n }\n return {\n token: creds.token,\n };\n }\n\n async getRepositoryFromIntegrations(repoUrl: string): Promise<{\n repository?: GithubRepository;\n errors?: GithubFetchError[];\n }> {\n const { data, errors } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n const resp = await octokit.rest.repos.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n });\n const repo = resp?.data;\n if (!repo) {\n return undefined;\n }\n return {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n },\n );\n\n return {\n repository: data,\n errors,\n };\n }\n\n async getOrganizationsFromIntegrations(\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n search?: string,\n ): Promise<GithubOrganizationResponse> {\n const orgs = new Map<string, GithubOrganization>();\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppOrgs(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n ghConfig,\n {\n credentialAccountLogin: credential.accountLogin,\n search,\n orgs,\n errors: dataFetchErrors,\n },\n )\n : await addGithubTokenOrgs(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n {\n search,\n orgs,\n pageNumber,\n pageSize,\n errors: dataFetchErrors,\n },\n );\n\n this.logger.debug(\n `Got ${resp.totalCount} org(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const orgList = Array.from(orgs.values());\n const totalCount = computeTotalCount(orgList, result.data, pageSize);\n return {\n organizations: orgList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n private async fetchUserTokenGithubIntegrationRepositories(\n userTokens: Record<string, string>,\n fetcher: (\n octokit: Octokit,\n credential: GithubCredentials,\n errors: Map<number, GithubFetchError>,\n ) => Promise<{ totalCount?: number }>,\n ): Promise<{ errors: GithubFetchError[]; totalCount: number | undefined }> {\n const allErrors: GithubFetchError[] = [];\n let totalCount: number | undefined;\n const ghConfigs = this.integrations.github.list().map(i => i.config);\n for (const ghConfig of ghConfigs) {\n const hostUrl = `https://${ghConfig.host}`;\n const token = userTokens[hostUrl];\n if (!token) {\n continue;\n }\n // Synthesize a token credential — same shape buildOcto already accepts\n const userCredential: GithubCredentials = { token, type: 'token' };\n\n // Intentionally no cache: user-token requests must not share the\n // server-credential ETag cache to avoid cross-user data leakage.\n const userOctokit = buildOcto(\n { logger: this.logger, cache: undefined },\n { credential: userCredential },\n ghConfig.apiBaseUrl,\n );\n if (!userOctokit) {\n continue;\n }\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const result = await fetcher(\n userOctokit,\n userCredential,\n dataFetchErrors,\n );\n totalCount = (totalCount ?? 0) + (result.totalCount ?? 0);\n dataFetchErrors.forEach(err => allErrors.push(err));\n }\n return { errors: allErrors, totalCount };\n }\n\n async getOrgRepositoriesFromIntegrations(\n orgName: string,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n userTokens?: Record<string, string>,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n\n // When a user token is present, build a user-scoped Octokit per integration\n // config and call addGithubTokenOrgRepositories with it. This scopes the\n // listing to repositories the user has access to within the given organization.\n // When absent, fall through to the existing server-credential path.\n if (userTokens && Object.keys(userTokens).length > 0) {\n const { errors: allErrors, totalCount } =\n await this.fetchUserTokenGithubIntegrationRepositories(\n userTokens,\n (userOctokit, userCredential, dataFetchErrors) =>\n addGithubTokenOrgRepositories(\n { logger: this.logger },\n userOctokit,\n userCredential,\n orgName,\n repositories,\n dataFetchErrors,\n { search, pageNumber, pageSize },\n ),\n );\n const repoList = Array.from(repositories.values());\n return { repositories: repoList, errors: allErrors, totalCount };\n }\n\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n let resp: { totalCount?: number };\n if (isGithubAppCredential(credential)) {\n if (credential.accountLogin !== orgName) {\n return {};\n }\n resp = await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n } else {\n resp = await addGithubTokenOrgRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n orgName,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n }\n this.logger.debug(\n `Got ${resp.totalCount} org repo(s) for ${ghConfig.host}`,\n );\n return {\n stopFetchingData: true,\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n return this.buildRepositoryResponse(repositories, result, pageSize);\n }\n\n /**\n * Returns GithubRepositoryResponse containing:\n * - a list of unique repositories the github integrations have access to\n * - a list of errors encountered by each app and/or token (if any exist)\n */\n async getRepositoriesFromIntegrations(\n search?: string,\n userTokens?: Record<string, string>,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n\n // When a user token is present, build a user-scoped Octokit per integration\n // config and call addGithubTokenRepositories with it. This makes\n // listForAuthenticatedUser return only repos the user personally has access to.\n // When absent, fall through to the existing server-credential path.\n if (userTokens && Object.keys(userTokens).length > 0) {\n const { errors: allErrors, totalCount } =\n await this.fetchUserTokenGithubIntegrationRepositories(\n userTokens,\n (userOctokit, userCredential, dataFetchErrors) =>\n addGithubTokenRepositories(\n { logger: this.logger },\n userOctokit,\n userCredential,\n repositories,\n dataFetchErrors,\n { search },\n ),\n );\n const repoList = Array.from(repositories.values());\n return { repositories: repoList, errors: allErrors, totalCount };\n }\n\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n )\n : await addGithubTokenRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n this.logger.debug(\n `Got ${resp.totalCount} repo(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n return this.buildRepositoryResponse(repositories, result, DefaultPageSize);\n }\n\n async filterLocationsAccessibleFromIntegrations(\n locationUrls: string[],\n ): Promise<string[]> {\n const locationGitOwnerMap = extractLocationOwnerMap(locationUrls);\n\n const allAccessibleAppOrgs = new Set<string>();\n const allAccessibleTokenOrgs = new Set<string>();\n const allAccessibleUsernames = new Set<string>();\n await fetchFromAllIntegrations(this.integrationDeps, this.integrations, {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n if (isGithubAppCredential(credential)) {\n const appOrgMap = await getAllAppOrgs(\n this.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n for (const [_, ghOrg] of appOrgMap) {\n allAccessibleAppOrgs.add(ghOrg.name);\n }\n } else {\n // find authenticated GitHub owner...\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n if (username) {\n allAccessibleUsernames.add(username);\n }\n // ... along with orgs accessible from the token auth\n (await octokit.paginate(octokit.rest.orgs.listForAuthenticatedUser))\n ?.map(org => org.login)\n ?.forEach(orgName => allAccessibleTokenOrgs.add(orgName));\n }\n return {};\n },\n });\n\n return locationUrls.filter(loc => {\n if (!locationGitOwnerMap.has(loc)) {\n return false;\n }\n const owner = locationGitOwnerMap.get(loc)!;\n return (\n allAccessibleAppOrgs.has(owner) ||\n allAccessibleTokenOrgs.has(owner) ||\n allAccessibleUsernames.has(owner)\n );\n });\n }\n\n async getPullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n ): Promise<{\n title?: string;\n body?: string;\n merged?: boolean;\n lastUpdated?: string;\n prSha?: string;\n prBranch?: string;\n }> {\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n const resp = await octokit.rest.pulls.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n });\n const pr = resp.data;\n return {\n title: pr.title,\n body: pr.body ?? undefined,\n merged: pr.merged,\n lastUpdated: pr.updated_at,\n prSha: pr.head.sha,\n prBranch: pr.head.ref,\n };\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async updatePullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n title?: string,\n body?: string,\n ): Promise<void> {\n await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n await octokit.rest.pulls.update({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n title: title,\n body: body,\n });\n return;\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error updating pull requests', error);\n throw error;\n }\n },\n );\n }\n\n async createOrUpdateFileInBranch(\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n ): Promise<void> {\n try {\n const ghConfig = this.integrations.github.byUrl(\n `https://github.com/${owner}/${repo}`,\n )?.config;\n if (!ghConfig) {\n throw new Error(\n `Could not find GH integration from https://github.com/${owner}/${repo}`,\n );\n }\n\n const credentials =\n await this.githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n for (const credential of credentials) {\n const octokit = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, owner },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n\n try {\n const { data: existingFile } = await octokit.rest.repos.getContent({\n owner: owner,\n repo: repo,\n path: fileName,\n ref: branchName,\n });\n // Response can either be a directory (array of files) or a single file element. In this case, we ensure it has the sha property to update it.\n if (Array.isArray(existingFile) || !('sha' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`,\n );\n }\n // If the file already exists, update it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n sha: existingFile.sha,\n branch: branchName,\n });\n } catch (error: any) {\n if (error.status === 404) {\n // If the file does not exist, create it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n branch: branchName,\n });\n } else {\n throw error;\n }\n }\n }\n } catch (error: any) {\n this.logger.error(\n `Error creating or updating file in branch ${branchName}`,\n error,\n );\n throw error;\n }\n }\n\n async findImportOpenPr(\n logger: LoggerService,\n input: {\n repoUrl: string;\n includeCatalogInfoContent?: boolean;\n },\n ): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n }> {\n const branchName = getBranchName(this.config);\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await findOpenPRForBranch(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n branchName,\n input.includeCatalogInfoContent,\n );\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async getCatalogInfoFile(\n logger: LoggerService,\n input: {\n repoUrl: string;\n prNumber: number;\n prHeadSha: string;\n },\n ): Promise<string | undefined> {\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await getCatalogInfoContentFromPR(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n input.prNumber,\n input.prHeadSha,\n );\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n 'Error fetching catalog info file content requests',\n error,\n );\n return undefined;\n }\n },\n );\n return data;\n }\n\n async submitPrToRepo(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n defaultBranch?: string;\n prTitle: string;\n prBody: string;\n catalogInfoContent: string;\n },\n ): Promise<{\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n errors?: string[];\n }> {\n const fileName = getCatalogFilename(this.config);\n const errors: any[] = [];\n\n const result = await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ): Promise<{\n successful: boolean;\n result?: {\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n };\n }> => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n // Check if there is already a catalogInfo in the default branch\n const catalogInfoFileExists = await fileExistsInDefaultBranch(\n logger,\n octo,\n owner,\n repo,\n fileName,\n input.defaultBranch,\n );\n if (catalogInfoFileExists) {\n // No need to create a PR => component will be imported as is\n return {\n successful: true,\n result: {\n hasChanges: false,\n },\n };\n }\n\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n\n const repoData = await octo.rest.repos.get({\n owner,\n repo,\n });\n const parentRef = await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${repoData.data.default_branch}`,\n });\n if (existingPrForBranch.prNum) {\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n const pullRequestResponse = await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: existingPrForBranch.prNum,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: existingPrForBranch.prNum,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n },\n };\n }\n\n let branchExists = false;\n try {\n await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${branchName}`,\n });\n branchExists = true;\n } catch (error: any) {\n if (error.status === 404) {\n await octo.rest.git.createRef({\n owner,\n repo,\n ref: `refs/heads/${branchName}`,\n sha: parentRef.data.object.sha,\n });\n } else {\n throw error;\n }\n }\n\n if (branchExists) {\n // update it in case it is outdated compared to the base branch\n try {\n await octo.repos.merge({\n owner: owner,\n repo: repo,\n base: branchName,\n head: repoData.data.default_branch,\n });\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n `Could not merge default branch ${repoData.data.default_branch} into import branch ${branchName}`,\n error,\n );\n }\n }\n\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n\n const pullRequestResponse = await octo.rest.pulls.create({\n owner,\n repo,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: pullRequestResponse.data.number,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n hasChanges: true,\n },\n };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't create PR in ${input.repoUrl}`,\n e,\n );\n errors.push(e.message);\n return { successful: false };\n }\n },\n },\n );\n\n if (result) {\n return result;\n }\n\n logger.warn(\n `Tried all possible GitHub credentials, but could not create PR in ${input.repoUrl}. Please try again later...`,\n );\n\n return {\n errors: errors,\n };\n }\n\n async hasFileInRepo(input: {\n repoUrl: string;\n defaultBranch?: string;\n fileName: string;\n }): Promise<boolean> {\n const fileExists = await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const exists = await fileExistsInDefaultBranch(\n this.logger,\n octo,\n owner,\n repo,\n input.fileName,\n input.defaultBranch,\n );\n if (exists === undefined) {\n return { successful: false };\n }\n return { successful: true, result: exists };\n },\n },\n );\n\n if (fileExists === undefined) {\n throw new Error(\n `Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`,\n );\n }\n\n return fileExists;\n }\n\n async closeImportPR(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n comment: string;\n },\n ): Promise<void> {\n await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n if (existingPrForBranch.prNum) {\n await closePRWithComment(\n octo,\n owner,\n repo,\n existingPrForBranch.prNum,\n input.comment,\n );\n }\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close PR in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async deleteImportBranch(input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n }): Promise<void> {\n await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n await octo.git.deleteRef({\n owner: owner,\n repo: repo,\n ref: `heads/${branchName}`,\n });\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close import PR and/or delete import branch in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async isRepoEmpty(input: { repoUrl: string }): Promise<boolean | undefined> {\n return await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const resp = await octo.rest.repos.listContributors({\n owner: owner,\n repo: repo,\n page: 1,\n per_page: 1,\n });\n const status = resp.status as 200 | 204;\n return { successful: true, result: status === 204 };\n },\n },\n );\n }\n}\n"],"names":["ScmIntegrations","CustomGithubCredentialsProvider","computeTotalCount","DefaultGithubCredentialsProvider","fetchFromMatchedIntegration","DefaultPageNumber","DefaultPageSize","fetchFromAllIntegrations","isGithubAppCredential","addGithubAppOrgs","addGithubTokenOrgs","buildOcto","addGithubTokenOrgRepositories","addGithubAppRepositories","addGithubTokenRepositories","extractLocationOwnerMap","getAllAppOrgs","logErrorIfNeeded","getBranchName","findOpenPRForBranch","getCatalogInfoContentFromPR","getCatalogFilename","executeFunctionOnFirstSuccessfulIntegration","fileExistsInDefaultBranch","pullRequestResponse","closePRWithComment"],"mappings":";;;;;;;;;;;;;;;;;;;AA4EO,MAAM,gBAAA,CAA0C;AAAA,EACpC,MAAA;AAAA,EACA,YAAA;AAAA,EACD,yBAAA;AAAA,EACC,MAAA;AAAA;AAAA,EAEA,KAAA;AAAA,EAEjB,WAAA,CACE,MAAA,EACA,MAAA,EACA,YAAA,EACA;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,YAAA,GAAeA,2BAAA,CAAgB,UAAA,CAAW,MAAM,CAAA;AACrD,IAAA,IAAA,CAAK,yBAAA,GACHC,gDAAA,CAAgC,gBAAA,CAAiB,IAAA,CAAK,YAAY,CAAA;AACpE,IAAA,IAAA,CAAK,KAAA,GAAQ,YAAA;AAAA,EACf;AAAA,EAEA,IAAY,eAAA,GAAkB;AAC5B,IAAA,OAAO;AAAA,MACL,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,OAAO,IAAA,CAAK,KAAA;AAAA,MACZ,2BAA2B,IAAA,CAAK;AAAA,KAClC;AAAA,EACF;AAAA,EAEA,IAAY,aAAA,GAAgB;AAC1B,IAAA,OAAO;AAAA,MACL,GAAG,IAAA,CAAK,eAAA;AAAA,MACR,QAAQ,IAAA,CAAK;AAAA,KACf;AAAA,EACF;AAAA,EAEQ,uBAAA,CACN,YAAA,EACA,MAAA,EACA,QAAA,EAC0B;AAC1B,IAAA,MAAM,QAAA,GAAW,KAAA,CAAM,IAAA,CAAK,YAAA,CAAa,QAAQ,CAAA;AACjD,IAAA,MAAM,UAAA,GAAaC,uBAAA,CAAkB,QAAA,EAAU,MAAA,CAAO,MAAM,QAAQ,CAAA;AACpE,IAAA,OAAO;AAAA,MACL,YAAA,EAAc,QAAA;AAAA,MACd,QAAQ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A,MAAM,SAAS,IAAA,CAAK,MAAA;AACpB,UAAA,OAAO,EAAE,UAAA,EAAY,IAAA,EAAM,MAAA,EAAQ,WAAW,GAAA,EAAI;AAAA,QACpD;AAAA;AACF,KACF;AAAA,EACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"githubApiService.cjs.js","sources":["../../src/github/githubApiService.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CacheService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n DefaultGithubCredentialsProvider,\n GithubCredentials,\n GithubCredentialType,\n GithubIntegrationConfig,\n ScmIntegrations,\n} from '@backstage/integration';\n\nimport { Octokit } from '@octokit/rest';\nimport gitUrlParse from 'git-url-parse';\n\nimport { getBranchName, getCatalogFilename } from '../catalog/catalogUtils';\nimport {\n computeTotalCount,\n extractLocationOwnerMap,\n logErrorIfNeeded,\n} from '../helpers';\nimport { GitApiService } from '../scm/GitApiService';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n} from '../service/handlers/handlers';\nimport { CustomGithubCredentialsProvider } from './GithubAppManager';\nimport {\n isGithubAppCredential,\n type ExtendedGithubCredentials,\n type GithubFetchError,\n type GithubOrganization,\n type GithubOrganizationResponse,\n type GithubRepository,\n type GithubRepositoryResponse,\n} from './types';\nimport { buildOcto } from './utils/ghUtils';\nimport {\n addGithubAppOrgs,\n addGithubTokenOrgs,\n getAllAppOrgs,\n} from './utils/orgUtils';\nimport {\n closePRWithComment,\n findOpenPRForBranch,\n getCatalogInfoContentFromPR,\n} from './utils/prUtils';\nimport {\n addGithubAppRepositories,\n addGithubTokenOrgRepositories,\n addGithubTokenRepositories,\n fileExistsInDefaultBranch,\n type ValidatedRepo,\n} from './utils/repoUtils';\nimport {\n executeFunctionOnFirstSuccessfulIntegration,\n fetchFromAllIntegrations,\n fetchFromMatchedIntegration,\n} from './utils/utils';\n\nexport class GithubApiService implements GitApiService {\n private readonly logger: LoggerService;\n private readonly integrations: ScmIntegrations;\n public readonly githubCredentialsProvider: CustomGithubCredentialsProvider;\n private readonly config: Config;\n // Cache for storing ETags (used for efficient caching of unchanged data returned by GitHub)\n private readonly cache: CacheService;\n\n constructor(\n logger: LoggerService,\n config: Config,\n cacheService: CacheService,\n ) {\n this.logger = logger;\n this.config = config;\n this.integrations = ScmIntegrations.fromConfig(config);\n this.githubCredentialsProvider =\n CustomGithubCredentialsProvider.fromIntegrations(this.integrations);\n this.cache = cacheService;\n }\n\n private get integrationDeps() {\n return {\n logger: this.logger,\n cache: this.cache,\n githubCredentialsProvider: this.githubCredentialsProvider,\n };\n }\n\n private get executionDeps() {\n return {\n ...this.integrationDeps,\n config: this.config,\n };\n }\n\n private buildRepositoryResponse(\n repositories: Map<string, GithubRepository>,\n result: { data: number[]; errors: Map<number, GithubFetchError> },\n pageSize: number,\n ): GithubRepositoryResponse {\n const repoList = Array.from(repositories.values());\n const totalCount = computeTotalCount(repoList, result.data, pageSize);\n return {\n repositories: repoList,\n errors: Array.from(result.errors.values()),\n totalCount,\n };\n }\n\n async getCredentials(repoUrl: string): Promise<{\n token: string;\n type: GithubCredentialType;\n }> {\n const provider = DefaultGithubCredentialsProvider.fromIntegrations(\n this.integrations,\n );\n const creds = await provider.getCredentials({\n url: repoUrl,\n });\n if (!creds || !creds.token) {\n throw new Error(`Token not configured for 'github' provider`);\n }\n return {\n token: creds.token,\n type: creds.type,\n };\n }\n\n /**\n * Returns a short-lived GitHub App installation token for the given repo URL.\n * Fails closed if only a classic PAT is available or no App installation exists.\n * Used by orchestrator import mode so long-lived PATs are never forwarded to SonataFlow.\n */\n async getAppInstallationCredentials(\n repoUrl: string,\n ): Promise<{ token: string }> {\n const creds = await this.getCredentials(repoUrl);\n if (creds.type !== 'app') {\n throw new Error(\n `Orchestrator import requires a GitHub App installation token for '${repoUrl}'. ` +\n `Configure integrations.github with an App that has access to this repository; ` +\n `classic personal access tokens are not forwarded in orchestrator mode.`,\n );\n }\n return {\n token: creds.token,\n };\n }\n\n async getRepositoryFromIntegrations(repoUrl: string): Promise<{\n repository?: GithubRepository;\n errors?: GithubFetchError[];\n }> {\n const { data, errors } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n const resp = await octokit.rest.repos.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n });\n const repo = resp?.data;\n if (!repo) {\n return undefined;\n }\n return {\n name: repo.name,\n full_name: repo.full_name,\n url: repo.url,\n html_url: repo.html_url,\n default_branch: repo.default_branch,\n updated_at: repo.updated_at,\n };\n },\n );\n\n return {\n repository: data,\n errors,\n };\n }\n\n async getOrganizationsFromIntegrations(\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n search?: string,\n ): Promise<GithubOrganizationResponse> {\n const orgs = new Map<string, GithubOrganization>();\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppOrgs(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n ghConfig,\n {\n credentialAccountLogin: credential.accountLogin,\n search,\n orgs,\n errors: dataFetchErrors,\n },\n )\n : await addGithubTokenOrgs(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n {\n search,\n orgs,\n pageNumber,\n pageSize,\n errors: dataFetchErrors,\n },\n );\n\n this.logger.debug(\n `Got ${resp.totalCount} org(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n const orgList = Array.from(orgs.values());\n const totalCount = computeTotalCount(orgList, result.data, pageSize);\n return {\n organizations: orgList,\n errors: Array.from(result.errors?.values() ?? []),\n totalCount,\n };\n }\n\n private async fetchUserTokenGithubIntegrationRepositories(\n userTokens: Record<string, string>,\n fetcher: (\n octokit: Octokit,\n credential: GithubCredentials,\n errors: Map<number, GithubFetchError>,\n ) => Promise<{ totalCount?: number }>,\n ): Promise<{ errors: GithubFetchError[]; totalCount: number | undefined }> {\n const allErrors: GithubFetchError[] = [];\n let totalCount: number | undefined;\n const ghConfigs = this.integrations.github.list().map(i => i.config);\n for (const ghConfig of ghConfigs) {\n const hostUrl = `https://${ghConfig.host}`;\n const token = userTokens[hostUrl];\n if (!token) {\n continue;\n }\n // Synthesize a token credential — same shape buildOcto already accepts\n const userCredential: GithubCredentials = { token, type: 'token' };\n\n // Intentionally no cache: user-token requests must not share the\n // server-credential ETag cache to avoid cross-user data leakage.\n const userOctokit = buildOcto(\n { logger: this.logger, cache: undefined },\n { credential: userCredential },\n ghConfig.apiBaseUrl,\n );\n if (!userOctokit) {\n continue;\n }\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const result = await fetcher(\n userOctokit,\n userCredential,\n dataFetchErrors,\n );\n totalCount = (totalCount ?? 0) + (result.totalCount ?? 0);\n dataFetchErrors.forEach(err => allErrors.push(err));\n }\n return { errors: allErrors, totalCount };\n }\n\n async getOrgRepositoriesFromIntegrations(\n orgName: string,\n search?: string,\n pageNumber: number = DefaultPageNumber,\n pageSize: number = DefaultPageSize,\n userTokens?: Record<string, string>,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n\n // When a user token is present, build a user-scoped Octokit per integration\n // config and call addGithubTokenOrgRepositories with it. This scopes the\n // listing to repositories the user has access to within the given organization.\n // When absent, fall through to the existing server-credential path.\n if (userTokens && Object.keys(userTokens).length > 0) {\n const { errors: allErrors, totalCount } =\n await this.fetchUserTokenGithubIntegrationRepositories(\n userTokens,\n (userOctokit, userCredential, dataFetchErrors) =>\n addGithubTokenOrgRepositories(\n { logger: this.logger },\n userOctokit,\n userCredential,\n orgName,\n repositories,\n dataFetchErrors,\n { search, pageNumber, pageSize },\n ),\n );\n const repoList = Array.from(repositories.values());\n return { repositories: repoList, errors: allErrors, totalCount };\n }\n\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n let resp: { totalCount?: number };\n if (isGithubAppCredential(credential)) {\n if (credential.accountLogin !== orgName) {\n return {};\n }\n resp = await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n } else {\n resp = await addGithubTokenOrgRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n orgName,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n }\n this.logger.debug(\n `Got ${resp.totalCount} org repo(s) for ${ghConfig.host}`,\n );\n return {\n stopFetchingData: true,\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n return this.buildRepositoryResponse(repositories, result, pageSize);\n }\n\n /**\n * Returns GithubRepositoryResponse containing:\n * - a list of unique repositories the github integrations have access to\n * - a list of errors encountered by each app and/or token (if any exist)\n */\n async getRepositoriesFromIntegrations(\n search?: string,\n userTokens?: Record<string, string>,\n ): Promise<GithubRepositoryResponse> {\n const repositories = new Map<string, GithubRepository>();\n\n // When a user token is present, build a user-scoped Octokit per integration\n // config and call addGithubTokenRepositories with it. This makes\n // listForAuthenticatedUser return only repos the user personally has access to.\n // When absent, fall through to the existing server-credential path.\n if (userTokens && Object.keys(userTokens).length > 0) {\n const { errors: allErrors, totalCount } =\n await this.fetchUserTokenGithubIntegrationRepositories(\n userTokens,\n (userOctokit, userCredential, dataFetchErrors) =>\n addGithubTokenRepositories(\n { logger: this.logger },\n userOctokit,\n userCredential,\n repositories,\n dataFetchErrors,\n { search },\n ),\n );\n const repoList = Array.from(repositories.values());\n return { repositories: repoList, errors: allErrors, totalCount };\n }\n\n const result = await fetchFromAllIntegrations(\n this.integrationDeps,\n this.integrations,\n {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n const dataFetchErrors = new Map<number, GithubFetchError>();\n const resp = isGithubAppCredential(credential)\n ? await addGithubAppRepositories(\n {\n logger: this.logger,\n githubCredentialsProvider: this.githubCredentialsProvider,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n )\n : await addGithubTokenRepositories(\n {\n logger: this.logger,\n },\n octokit,\n credential,\n repositories,\n dataFetchErrors,\n {\n search,\n },\n );\n this.logger.debug(\n `Got ${resp.totalCount} repo(s) for ${ghConfig.host}`,\n );\n return {\n result: resp.totalCount ?? 0,\n errors: Array.from(dataFetchErrors.values()),\n };\n },\n },\n );\n\n return this.buildRepositoryResponse(repositories, result, DefaultPageSize);\n }\n\n async filterLocationsAccessibleFromIntegrations(\n locationUrls: string[],\n ): Promise<string[]> {\n const locationGitOwnerMap = extractLocationOwnerMap(locationUrls);\n\n const allAccessibleAppOrgs = new Set<string>();\n const allAccessibleTokenOrgs = new Set<string>();\n const allAccessibleUsernames = new Set<string>();\n await fetchFromAllIntegrations(this.integrationDeps, this.integrations, {\n dataFetcher: async (\n octokit: Octokit,\n credential: ExtendedGithubCredentials,\n ghConfig: GithubIntegrationConfig,\n ) => {\n if (isGithubAppCredential(credential)) {\n const appOrgMap = await getAllAppOrgs(\n this.githubCredentialsProvider,\n ghConfig,\n credential.accountLogin,\n );\n for (const [_, ghOrg] of appOrgMap) {\n allAccessibleAppOrgs.add(ghOrg.name);\n }\n } else {\n // find authenticated GitHub owner...\n const username = (await octokit.rest.users.getAuthenticated())?.data\n ?.login;\n if (username) {\n allAccessibleUsernames.add(username);\n }\n // ... along with orgs accessible from the token auth\n (await octokit.paginate(octokit.rest.orgs.listForAuthenticatedUser))\n ?.map(org => org.login)\n ?.forEach(orgName => allAccessibleTokenOrgs.add(orgName));\n }\n return {};\n },\n });\n\n return locationUrls.filter(loc => {\n if (!locationGitOwnerMap.has(loc)) {\n return false;\n }\n const owner = locationGitOwnerMap.get(loc)!;\n return (\n allAccessibleAppOrgs.has(owner) ||\n allAccessibleTokenOrgs.has(owner) ||\n allAccessibleUsernames.has(owner)\n );\n });\n }\n\n async getPullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n ): Promise<{\n title?: string;\n body?: string;\n merged?: boolean;\n lastUpdated?: string;\n prSha?: string;\n prBranch?: string;\n }> {\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n const resp = await octokit.rest.pulls.get({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n });\n const pr = resp.data;\n return {\n title: pr.title,\n body: pr.body ?? undefined,\n merged: pr.merged,\n lastUpdated: pr.updated_at,\n prSha: pr.head.sha,\n prBranch: pr.head.ref,\n };\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async updatePullRequest(\n repoUrl: string,\n pullRequestNumber: number,\n title?: string,\n body?: string,\n ): Promise<void> {\n await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n repoUrl,\n async (octokit, gitUrl) => {\n try {\n await octokit.rest.pulls.update({\n owner: gitUrl.owner,\n repo: gitUrl.name,\n pull_number: pullRequestNumber,\n title: title,\n body: body,\n });\n return;\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error updating pull requests', error);\n throw error;\n }\n },\n );\n }\n\n async createOrUpdateFileInBranch(\n owner: string,\n repo: string,\n branchName: string,\n fileName: string,\n fileContent: string,\n ): Promise<void> {\n try {\n const ghConfig = this.integrations.github.byUrl(\n `https://github.com/${owner}/${repo}`,\n )?.config;\n if (!ghConfig) {\n throw new Error(\n `Could not find GH integration from https://github.com/${owner}/${repo}`,\n );\n }\n\n const credentials =\n await this.githubCredentialsProvider.getAllCredentials({\n host: ghConfig.host,\n });\n\n if (credentials.length === 0) {\n throw new Error(`No credentials for GH integration`);\n }\n\n for (const credential of credentials) {\n const octokit = buildOcto(\n {\n logger: this.logger,\n cache: this.cache,\n },\n { credential, owner },\n ghConfig.apiBaseUrl,\n );\n if (!octokit) {\n continue;\n }\n\n try {\n const { data: existingFile } = await octokit.rest.repos.getContent({\n owner: owner,\n repo: repo,\n path: fileName,\n ref: branchName,\n });\n // Response can either be a directory (array of files) or a single file element. In this case, we ensure it has the sha property to update it.\n if (Array.isArray(existingFile) || !('sha' in existingFile)) {\n throw new Error(\n `The content at path ${fileName} is not a file or the response from GitHub does not contain the 'sha' property.`,\n );\n }\n // If the file already exists, update it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n sha: existingFile.sha,\n branch: branchName,\n });\n } catch (error: any) {\n if (error.status === 404) {\n // If the file does not exist, create it\n await octokit.rest.repos.createOrUpdateFileContents({\n owner,\n repo,\n path: fileName,\n message: `Add ${fileName} config file`,\n content: btoa(fileContent),\n branch: branchName,\n });\n } else {\n throw error;\n }\n }\n }\n } catch (error: any) {\n this.logger.error(\n `Error creating or updating file in branch ${branchName}`,\n error,\n );\n throw error;\n }\n }\n\n async findImportOpenPr(\n logger: LoggerService,\n input: {\n repoUrl: string;\n includeCatalogInfoContent?: boolean;\n },\n ): Promise<{\n prNum?: number;\n prUrl?: string;\n prTitle?: string;\n prBody?: string;\n prCatalogInfoContent?: string;\n lastUpdate?: string;\n }> {\n const branchName = getBranchName(this.config);\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await findOpenPRForBranch(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n branchName,\n input.includeCatalogInfoContent,\n );\n } catch (error: any) {\n logErrorIfNeeded(this.logger, 'Error fetching pull requests', error);\n return undefined;\n }\n },\n );\n return data ?? {};\n }\n\n async getCatalogInfoFile(\n logger: LoggerService,\n input: {\n repoUrl: string;\n prNumber: number;\n prHeadSha: string;\n },\n ): Promise<string | undefined> {\n const { data } = await fetchFromMatchedIntegration(\n this.integrationDeps,\n this.integrations,\n input.repoUrl,\n async (octokit, gitUrl) => {\n try {\n return await getCatalogInfoContentFromPR(\n logger,\n this.config,\n octokit,\n gitUrl.organization,\n gitUrl.name,\n input.prNumber,\n input.prHeadSha,\n );\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n 'Error fetching catalog info file content requests',\n error,\n );\n return undefined;\n }\n },\n );\n return data;\n }\n\n async submitPrToRepo(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n defaultBranch?: string;\n prTitle: string;\n prBody: string;\n catalogInfoContent: string;\n },\n ): Promise<{\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n errors?: string[];\n }> {\n const fileName = getCatalogFilename(this.config);\n const errors: any[] = [];\n\n const result = await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (\n validatedRepo: ValidatedRepo,\n octo: Octokit,\n ): Promise<{\n successful: boolean;\n result?: {\n prUrl?: string;\n prNumber?: number;\n hasChanges?: boolean;\n lastUpdate?: string;\n };\n }> => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n // Check if there is already a catalogInfo in the default branch\n const catalogInfoFileExists = await fileExistsInDefaultBranch(\n logger,\n octo,\n owner,\n repo,\n fileName,\n input.defaultBranch,\n );\n if (catalogInfoFileExists) {\n // No need to create a PR => component will be imported as is\n return {\n successful: true,\n result: {\n hasChanges: false,\n },\n };\n }\n\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n\n const repoData = await octo.rest.repos.get({\n owner,\n repo,\n });\n const parentRef = await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${repoData.data.default_branch}`,\n });\n if (existingPrForBranch.prNum) {\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n const pullRequestResponse = await octo.rest.pulls.update({\n owner,\n repo,\n pull_number: existingPrForBranch.prNum,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: existingPrForBranch.prNum,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n },\n };\n }\n\n let branchExists = false;\n try {\n await octo.rest.git.getRef({\n owner,\n repo,\n ref: `heads/${branchName}`,\n });\n branchExists = true;\n } catch (error: any) {\n if (error.status === 404) {\n await octo.rest.git.createRef({\n owner,\n repo,\n ref: `refs/heads/${branchName}`,\n sha: parentRef.data.object.sha,\n });\n } else {\n throw error;\n }\n }\n\n if (branchExists) {\n // update it in case it is outdated compared to the base branch\n try {\n await octo.repos.merge({\n owner: owner,\n repo: repo,\n base: branchName,\n head: repoData.data.default_branch,\n });\n } catch (error: any) {\n logErrorIfNeeded(\n this.logger,\n `Could not merge default branch ${repoData.data.default_branch} into import branch ${branchName}`,\n error,\n );\n }\n }\n\n await this.createOrUpdateFileInBranch(\n owner,\n repo,\n branchName,\n fileName,\n input.catalogInfoContent,\n );\n\n const pullRequestResponse = await octo.rest.pulls.create({\n owner,\n repo,\n title: input.prTitle,\n body: input.prBody,\n head: branchName,\n base: repoData.data.default_branch,\n });\n return {\n successful: true,\n result: {\n prNumber: pullRequestResponse.data.number,\n prUrl: pullRequestResponse.data.html_url,\n lastUpdate: pullRequestResponse.data.updated_at,\n hasChanges: true,\n },\n };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't create PR in ${input.repoUrl}`,\n e,\n );\n errors.push(e.message);\n return { successful: false };\n }\n },\n },\n );\n\n if (result) {\n return result;\n }\n\n logger.warn(\n `Tried all possible GitHub credentials, but could not create PR in ${input.repoUrl}. Please try again later...`,\n );\n\n return {\n errors: errors,\n };\n }\n\n async hasFileInRepo(input: {\n repoUrl: string;\n defaultBranch?: string;\n fileName: string;\n }): Promise<boolean> {\n const fileExists = await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const exists = await fileExistsInDefaultBranch(\n this.logger,\n octo,\n owner,\n repo,\n input.fileName,\n input.defaultBranch,\n );\n if (exists === undefined) {\n return { successful: false };\n }\n return { successful: true, result: exists };\n },\n },\n );\n\n if (fileExists === undefined) {\n throw new Error(\n `Could not determine if repo at ${input.repoUrl} already has a file named ${input.fileName} in its default branch (${input.defaultBranch})`,\n );\n }\n\n return fileExists;\n }\n\n async closeImportPR(\n logger: LoggerService,\n input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n comment: string;\n },\n ): Promise<void> {\n await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n const existingPrForBranch = await findOpenPRForBranch(\n logger,\n this.config,\n octo,\n owner,\n repo,\n branchName,\n );\n if (existingPrForBranch.prNum) {\n await closePRWithComment(\n octo,\n owner,\n repo,\n existingPrForBranch.prNum,\n input.comment,\n );\n }\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close PR in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async deleteImportBranch(input: {\n repoUrl: string;\n gitUrl: gitUrlParse.GitUrl;\n }): Promise<void> {\n await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo, branchName } = validatedRepo;\n try {\n await octo.git.deleteRef({\n owner: owner,\n repo: repo,\n ref: `heads/${branchName}`,\n });\n return { successful: true };\n } catch (e: any) {\n logErrorIfNeeded(\n this.logger,\n `Couldn't close import PR and/or delete import branch in ${input.repoUrl}`,\n e,\n );\n return { successful: false };\n }\n },\n },\n );\n }\n\n async isRepoEmpty(input: { repoUrl: string }): Promise<boolean | undefined> {\n return await executeFunctionOnFirstSuccessfulIntegration(\n this.executionDeps,\n this.integrations,\n {\n repoUrl: input.repoUrl,\n fn: async (validatedRepo: ValidatedRepo, octo: Octokit) => {\n const { owner, repo } = validatedRepo;\n const resp = await octo.rest.repos.listContributors({\n owner: owner,\n repo: repo,\n page: 1,\n per_page: 1,\n });\n const status = resp.status as 200 | 204;\n return { successful: true, result: status === 204 };\n },\n },\n );\n }\n}\n"],"names":["ScmIntegrations","CustomGithubCredentialsProvider","computeTotalCount","DefaultGithubCredentialsProvider","fetchFromMatchedIntegration","DefaultPageNumber","DefaultPageSize","fetchFromAllIntegrations","isGithubAppCredential","addGithubAppOrgs","addGithubTokenOrgs","buildOcto","addGithubTokenOrgRepositories","addGithubAppRepositories","addGithubTokenRepositories","extractLocationOwnerMap","getAllAppOrgs","logErrorIfNeeded","getBranchName","findOpenPRForBranch","getCatalogInfoContentFromPR","getCatalogFilename","executeFunctionOnFirstSuccessfulIntegration","fileExistsInDefaultBranch","pullRequestResponse","closePRWithComment"],"mappings":";;;;;;;;;;;;;;;;;;;AA6EO,MAAM,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AA,EAAO,IAAA,EAAK,GAAI,aAAA;AACxB,UAAA,MAAM,IAAA,GAAO,MAAM,IAAA,CAAK,IAAA,CAAK,MAAM,gBAAA,CAAiB;AAAA,YAClD,KAAA;AAAA,YACA,IAAA;AAAA,YACA,IAAA,EAAM,CAAA;AAAA,YACN,QAAA,EAAU;AAAA,WACX,CAAA;AACD,UAAA,MAAM,SAAS,IAAA,CAAK,MAAA;AACpB,UAAA,OAAO,EAAE,UAAA,EAAY,IAAA,EAAM,MAAA,EAAQ,WAAW,GAAA,EAAI;AAAA,QACpD;AAAA;AACF,KACF;AAAA,EACF;AACF;;;;"}
|
|
@@ -632,7 +632,7 @@ async function findTaskImportStatusByRepo(deps, repoUrl, skipTasks) {
|
|
|
632
632
|
responseBody: result
|
|
633
633
|
};
|
|
634
634
|
}
|
|
635
|
-
async function findOrchestratorImportStatusByRepo(deps, repoUrl,
|
|
635
|
+
async function findOrchestratorImportStatusByRepo(deps, repoUrl, skipWorkflows) {
|
|
636
636
|
deps.logger.debug(
|
|
637
637
|
`Getting orchestrator workflow import job status for ${repoUrl}.`
|
|
638
638
|
);
|
|
@@ -660,6 +660,10 @@ async function findOrchestratorImportStatusByRepo(deps, repoUrl, token, skipWork
|
|
|
660
660
|
}
|
|
661
661
|
if (workflow.instanceId) {
|
|
662
662
|
const baseUrl = await deps.discovery.getBaseUrl("orchestrator");
|
|
663
|
+
const { token } = await deps.auth.getPluginRequestToken({
|
|
664
|
+
onBehalfOf: await deps.httpAuth.credentials(deps.req),
|
|
665
|
+
targetPluginId: "orchestrator"
|
|
666
|
+
});
|
|
663
667
|
const orchestratorApi = new backstagePluginOrchestratorCommon.DefaultApi(new backstagePluginOrchestratorCommon.Configuration(), baseUrl);
|
|
664
668
|
const response = await orchestratorApi.getInstanceById(
|
|
665
669
|
workflow.instanceId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bulkImports.cjs.js","sources":["../../../../src/service/handlers/import/bulkImports.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AuthService,\n DiscoveryService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport { NotFoundError } from '@backstage/errors';\n\nimport gitUrlParse from 'git-url-parse';\n\nimport {\n Configuration,\n DefaultApi,\n} from '@red-hat-developer-hub/backstage-plugin-orchestrator-common';\n\nimport { CatalogHttpClient } from '../../../catalog/catalogHttpClient';\nimport type { CatalogInfoGenerator } from '../../../catalog/catalogInfoGenerator';\nimport {\n getCatalogFilename,\n getCatalogUrl,\n} from '../../../catalog/catalogUtils';\nimport {\n OrchestratorWorkflow,\n OrchestratorWorkflowDao,\n RepositoryDao,\n RepositoryName,\n ScaffolderTaskDao,\n TaskLocationsDao,\n} from '../../../database/repositoryDao';\nimport type { Components, Paths } from '../../../generated/openapi';\nimport type { GithubApiService } from '../../../github';\nimport { GitlabApiService } from '../../../gitlab';\nimport {\n getNestedValue,\n logErrorIfNeeded,\n paginateArray,\n parseGitURLForApprovalTool,\n} from '../../../helpers';\nimport { GitApiService } from '../../../scm/GitApiService';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n DefaultSortColumn,\n DefaultSortOrder,\n type HandlerResponse,\n} from '../handlers';\n\ntype CreateImportDryRunStatus =\n | 'CATALOG_ENTITY_CONFLICT'\n | 'CATALOG_INFO_FILE_EXISTS_IN_REPO'\n | 'CODEOWNERS_FILE_NOT_FOUND_IN_REPO'\n | 'REPO_EMPTY';\n\ntype FindAllImportsResponse =\n Components.Schemas.Import[] | Components.Schemas.ImportJobListV2;\n\nexport function sortImports(\n imports: Components.Schemas.Import[],\n sortColumn: Components.Parameters.SortColumnQueryParam = DefaultSortColumn,\n sortOrder: Components.Parameters.SortOrderQueryParam = DefaultSortOrder,\n) {\n imports.sort((a, b) => {\n const value1 = getNestedValue(a, sortColumn);\n const value2 = getNestedValue(b, sortColumn);\n // Handle cases where values are undefined\n if (value1 === undefined && value2 === undefined) return 0;\n if (value1 === undefined) return sortOrder === 'asc' ? -1 : 1;\n if (value2 === undefined) return sortOrder === 'asc' ? 1 : -1;\n\n if (sortColumn === 'lastUpdate') {\n const date1 = new Date(value1); // Convert string to Date object\n const date2 = new Date(value2); // Convert string to Date object\n // Compare dates\n return sortOrder === 'asc'\n ? date2.getTime() - date1.getTime()\n : date1.getTime() - date2.getTime();\n }\n // Compare values based on sort order\n return sortOrder === 'asc'\n ? value1.localeCompare(value2)\n : value2.localeCompare(value1);\n });\n}\n\nexport async function findAllImports(\n deps: {\n logger: LoggerService;\n config: Config;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n requestHeaders?: {\n apiVersion?: Paths.FindAllImports.Parameters.ApiVersion;\n },\n queryParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n sortColumn?: Components.Parameters.SortColumnQueryParam;\n sortOrder?: Components.Parameters.SortOrderQueryParam;\n },\n): Promise<HandlerResponse<FindAllImportsResponse>> {\n const apiVersion = requestHeaders?.apiVersion ?? 'v1';\n const search = queryParams?.search;\n const pageNumber = queryParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = queryParams?.pageSize ?? DefaultPageSize;\n const sortColumn = queryParams?.sortColumn ?? DefaultSortColumn;\n const sortOrder = queryParams?.sortOrder ?? DefaultSortOrder;\n\n const catalogFilename = getCatalogFilename(deps.config);\n\n const allLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations(\n search,\n pageNumber,\n pageSize,\n )\n ).uniqueCatalogUrlLocations;\n\n // resolve default branches for each unique repo URL from GH,\n // because we cannot easily determine that from the location target URL.\n // It can be 'main' or something more convoluted like 'our/awesome/main'.\n const defaultBranchByRepoUrl = await resolveReposDefaultBranches(\n deps.logger,\n deps.gitlabApiService,\n deps.githubApiService,\n allLocations.keys(),\n catalogFilename,\n );\n\n // filter out locations that do not match what we are expecting, i.e.:\n // an URL to a catalog-info YAML file at the root of the repo\n const importCandidates = findImportCandidates(\n allLocations.keys(),\n defaultBranchByRepoUrl,\n catalogFilename,\n );\n\n // Keep only repos that are accessible from the configured GH/GL integrations\n const importsReachableFromGHIntegrations =\n await deps.githubApiService.filterLocationsAccessibleFromIntegrations(\n importCandidates.filter(val => {\n return parseGitURLForApprovalTool(val) === 'GIT';\n }),\n );\n\n const importsReachableFromGLIntegrations =\n await deps.gitlabApiService.filterLocationsAccessibleFromIntegrations(\n importCandidates.filter(val => {\n return parseGitURLForApprovalTool(val) === 'GITLAB';\n }),\n );\n\n // Merge the two lists together and map the appropriate approvalTool\n const mergedReachbleFromIntegrations = importsReachableFromGHIntegrations\n .map(val => {\n return {\n loc: val,\n approvalTool: 'GIT',\n };\n })\n .concat(\n importsReachableFromGLIntegrations.map(val => {\n return {\n loc: val,\n approvalTool: 'GITLAB',\n };\n }),\n );\n\n const repoUrlToLocation = new Map<string, string>();\n\n // now fetch the import statuses in different promises\n const importStatusPromises: Promise<\n HandlerResponse<Components.Schemas.Import>\n >[] = [];\n for (const imports of mergedReachbleFromIntegrations) {\n const repoUrl = repoUrlFromLocation(imports.loc);\n if (!repoUrl) {\n continue;\n }\n repoUrlToLocation.set(repoUrl, imports.loc);\n\n importStatusPromises.push(\n findImportStatusByRepo(\n {\n logger: deps.logger,\n config: deps.config,\n gitApiService:\n imports.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService,\n catalogHttpClient: deps.catalogHttpClient,\n approvalTool: imports.approvalTool,\n },\n repoUrl,\n defaultBranchByRepoUrl.get(repoUrl),\n false,\n ),\n );\n }\n\n const result = await Promise.all(importStatusPromises);\n const imports = result\n .filter(res => res.responseBody)\n .map(res => res.responseBody!)\n .map(res => {\n const key = res?.repository?.url;\n const location = key ? repoUrlToLocation.get(key) : undefined;\n return {\n ...res,\n source: location ? allLocations.get(location)?.source : undefined,\n };\n });\n\n // sorting the output to make it deterministic and easy to navigate in the UI\n\n sortImports(imports, sortColumn, sortOrder);\n const paginated = paginateArray(imports, pageNumber, pageSize);\n if (apiVersion === 'v1') {\n return {\n statusCode: 200,\n responseBody: paginated.result,\n };\n }\n return {\n statusCode: 200,\n responseBody: {\n imports: paginated.result,\n totalCount: paginated.totalCount,\n page: pageNumber,\n size: pageSize,\n },\n };\n}\n\nasync function resolveReposDefaultBranches(\n logger: LoggerService,\n gitlabApiService: GitlabApiService,\n githubApiService: GithubApiService,\n allLocations: Iterable<string>,\n catalogFilename: string,\n) {\n const defaultBranchByRepoUrlPromises: Promise<{\n repoUrl: string;\n defaultBranch?: string;\n }>[] = [];\n for (const loc of allLocations) {\n // loc has the following format: https://github.com/<org>/<repo>/blob/<default-branch>/catalog-info.yaml\n // but it can have a more convoluted format like 'https://github.com/redhat-developer/rhdh-plugins/blob/main/plugins/scaffolder-annotator-action/examples/templates/01-scaffolder-template.yaml'\n // if registered manually from the 'Register existing component' feature in Backstage.\n if (!loc.endsWith(catalogFilename)) {\n logger.debug(\n `Ignored location ${loc} because it does not point to a file named ${catalogFilename}`,\n );\n continue;\n }\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n // Have to do this for Both the gitlab/github, possibly a better way?\n // Should probably parse the URL to figure out which to use?\n defaultBranchByRepoUrlPromises.push(\n (parseGitURLForApprovalTool(repoUrl) === 'GITLAB'\n ? gitlabApiService\n : githubApiService\n )\n .getRepositoryFromIntegrations(repoUrl)\n .then(resp => {\n return { repoUrl, defaultBranch: resp?.repository?.default_branch };\n })\n .catch((err: any) => {\n logErrorIfNeeded(\n logger,\n `Ignored repo ${repoUrl} due to an error while fetching details from GitHub`,\n err,\n );\n return {\n repoUrl,\n defaultBranch: undefined,\n };\n }),\n );\n }\n const defaultBranchesResponses = await Promise.all(\n defaultBranchByRepoUrlPromises,\n );\n return new Map(\n defaultBranchesResponses\n .flat()\n .filter(r => r.defaultBranch)\n .map(r => [r.repoUrl, r.defaultBranch!]),\n );\n}\n\nfunction repoUrlFromLocation(loc: string) {\n const split = loc.split('/blob/');\n if (split.length < 2) {\n return undefined;\n }\n return split[0];\n}\n\nfunction findImportCandidates(\n allLocations: Iterable<string>,\n defaultBranchByRepoUrl: Map<string, string>,\n catalogFilename: string,\n) {\n const filteredLocations: string[] = [];\n for (const loc of allLocations) {\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n\n const defaultBranch = defaultBranchByRepoUrl.get(repoUrl);\n if (!defaultBranch) {\n continue;\n }\n if (loc !== `${repoUrl}/blob/${defaultBranch}/${catalogFilename}`) {\n // Because users can use the \"Register existing component\" workflow to register a Location\n // using any file path in the repo, we consider a repository as an Import Location only\n // if it is at the root of the repository, because that is what the import PR ultimately does.\n continue;\n }\n filteredLocations.push(loc);\n }\n return filteredLocations;\n}\n\nasync function createPR(\n gitApiService: GitApiService,\n logger: LoggerService,\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n catalogInfoGenerator: CatalogInfoGenerator,\n config: Config,\n) {\n const appTitle =\n config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = config.getString('app.baseUrl');\n const catalogFileName = getCatalogFilename(config);\n return await gitApiService.submitPrToRepo(logger, {\n repoUrl: req.repository.url,\n gitUrl: gitUrl,\n defaultBranch: req.repository.defaultBranch,\n catalogInfoContent:\n req.catalogInfoContent ??\n (await catalogInfoGenerator.generateDefaultCatalogInfoContent(\n req.repository.url,\n )),\n prTitle:\n req[req.approvalTool === 'GITLAB' ? 'gitlab' : 'github']?.pullRequest\n ?.title ?? `Add ${catalogFileName}`,\n prBody:\n req[req.approvalTool === 'GITLAB' ? 'gitlab' : 'github']?.pullRequest\n ?.body ??\n `\nThis pull request adds a **Backstage entity metadata file** to this repository so that the component can be added to a Backstage application.\n\nAfter this pull request is merged, the component will become available in the [${appTitle} software catalog](${appBaseUrl}).\n\nFor more information, read an [overview of the Backstage software catalog](https://backstage.io/docs/features/software-catalog/).\n`,\n });\n}\n\nasync function handleAddedReposFromCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Components.Schemas.ImportRequest[],\n) {\n const result: Components.Schemas.Import[] = [];\n\n for (const req of importRequests) {\n // Check if repo is already imported\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const hasLocation =\n await deps.catalogHttpClient.verifyLocationExistence(repoCatalogUrl);\n if (!hasLocation) {\n continue;\n }\n const gitApiService =\n req.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService;\n const hasCatalogInfoFileInRepo = await gitApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (!hasCatalogInfoFileInRepo) {\n continue;\n }\n\n const ghRepo = await gitApiService.getRepositoryFromIntegrations(\n req.repository.url,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n\n const gitUrl = gitUrlParse(req.repository.url);\n result.push({\n status: 'ADDED',\n lastUpdate: ghRepo?.repository?.updated_at ?? undefined,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function handlePrCreationRequest(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n): Promise<Components.Schemas.Import> {\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const gitApiService =\n req.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService;\n const prToRepo = await createPR(\n gitApiService,\n deps.logger,\n req,\n gitUrl,\n deps.catalogInfoGenerator,\n deps.config,\n );\n if (prToRepo.errors && prToRepo.errors.length > 0) {\n return {\n errors: prToRepo.errors,\n status: 'PR_ERROR',\n repository: req.repository,\n };\n }\n if (prToRepo.prUrl) {\n deps.logger.debug(`Created new PR from request: ${prToRepo.prUrl}`);\n }\n\n // Create Location\n await deps.catalogHttpClient.possiblyCreateLocation(repoCatalogUrl);\n\n if (prToRepo.hasChanges === false) {\n deps.logger.debug(\n `No bulk import PR created on ${req.repository.url} since its default branch (${req.repository.defaultBranch}) already contains a catalog-info file`,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n return {\n status: 'ADDED',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n };\n }\n\n return {\n approvalTool: req.approvalTool ?? 'GIT',\n errors: prToRepo.errors,\n status: 'WAIT_PR_APPROVAL',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n [req.approvalTool === 'GITLAB' ? 'gitlab' : 'github']: {\n pullRequest: {\n url: prToRepo.prUrl,\n number: prToRepo.prNumber,\n },\n },\n };\n}\n\nexport async function createImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n reqParams: {\n importRequests: Paths.CreateImportJobs.RequestBody;\n dryRun?: boolean;\n },\n): Promise<HandlerResponse<Components.Schemas.Import[]>> {\n const dryRun = reqParams.dryRun ?? false;\n const importRequests = reqParams.importRequests;\n deps.logger.debug(\n `Handling request to import ${importRequests?.length} repo(s) (dryRun=${dryRun})..`,\n );\n\n if (importRequests.length === 0) {\n deps.logger.debug('Missing import requests from request body');\n return {\n statusCode: 400,\n responseBody: [],\n };\n }\n\n if (dryRun) {\n return {\n statusCode: 202,\n responseBody: await dryRunCreateImportJobs(deps, importRequests),\n };\n }\n\n const result: Components.Schemas.Import[] = [];\n\n const addedRepos = await handleAddedReposFromCreateImportJobs(\n deps,\n importRequests,\n );\n result.push(...addedRepos);\n const addedReposMap = new Map(\n addedRepos.map(res => [res.repository?.url, res]),\n );\n const remainingRequests = importRequests.filter(\n req => !addedReposMap.has(req.repository.url),\n );\n\n for (const req of remainingRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n // Create PR\n try {\n result.push(await handlePrCreationRequest(deps, req, gitUrl));\n } catch (error: any) {\n result.push({\n errors: [error.message],\n status: 'PR_ERROR',\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n } as Components.Schemas.Import);\n }\n }\n\n sortImports(result);\n\n return {\n statusCode: 202,\n responseBody: result,\n };\n}\n\nasync function dryRunCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Paths.CreateImportJobs.RequestBody,\n) {\n const result: Components.Schemas.Import[] = [];\n for (const req of importRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n const dryRunChecks = await performDryRunChecks(deps, req);\n if (dryRunChecks.errors?.length > 0) {\n deps.logger.warn(\n `Errors while performing dry-run checks: ${dryRunChecks.errors}`,\n );\n }\n result.push({\n errors: dryRunChecks.dryRunStatuses,\n catalogEntityName: req.catalogEntityName,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function performDryRunChecks(\n deps: {\n logger: LoggerService;\n auth: AuthService;\n config: Config;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n): Promise<{ dryRunStatuses: CreateImportDryRunStatus[]; errors: string[] }> {\n const checkCatalog = async (\n catalogEntityName: string,\n ): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const hasEntity =\n await deps.catalogHttpClient.hasEntityInCatalog(catalogEntityName);\n if (hasEntity) {\n return { dryRunStatuses: ['CATALOG_ENTITY_CONFLICT'] };\n }\n return {};\n };\n\n const gitApiService =\n req.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService;\n const checkEmptyRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const empty = await gitApiService.isRepoEmpty({\n repoUrl: req.repository.url,\n });\n if (empty) {\n return {\n dryRunStatuses: ['REPO_EMPTY'],\n };\n }\n return {};\n };\n\n const checkCatalogInfoPresenceInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const exists = await gitApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (exists) {\n return {\n dryRunStatuses: ['CATALOG_INFO_FILE_EXISTS_IN_REPO'],\n };\n }\n return {};\n };\n\n const checkCodeOwnersFileInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const gitDirLocation =\n req.approvalTool === 'GITLAB' ? '.gitlab' : '.github';\n const exists = await gitApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: `${gitDirLocation}/CODEOWNERS`,\n });\n if (!exists) {\n return {\n dryRunStatuses: ['CODEOWNERS_FILE_NOT_FOUND_IN_REPO'],\n };\n }\n return {};\n };\n\n const dryRunStatuses: CreateImportDryRunStatus[] = [];\n const errors: string[] = [];\n const allChecksFn = [checkEmptyRepo(), checkCatalogInfoPresenceInRepo()];\n if (req.catalogEntityName?.trim()) {\n allChecksFn.push(checkCatalog(req.catalogEntityName));\n }\n if (req.codeOwnersFileAsEntityOwner) {\n allChecksFn.push(checkCodeOwnersFileInRepo());\n }\n const allChecks = await Promise.all(allChecksFn);\n allChecks.flat().forEach(res => {\n if (res.dryRunStatuses) {\n dryRunStatuses.push(...res.dryRunStatuses);\n }\n if (res.errors) {\n errors.push(...res.errors);\n }\n });\n\n dryRunStatuses.sort((a, b) => a.localeCompare(b));\n\n return {\n dryRunStatuses,\n errors,\n };\n}\n\nexport async function findImportStatusByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n gitApiService: GitlabApiService | GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n approvalTool: string | undefined;\n },\n repoUrl: string,\n defaultBranch?: string,\n includeCatalogInfoContent?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(`Getting bulk import job status for ${repoUrl}..`);\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n defaultBranch,\n },\n approvalTool: deps.approvalTool,\n status: null,\n } as Components.Schemas.Import;\n try {\n // Check to see if there are any PR\n const openImportPr = await deps.gitApiService.findImportOpenPr(\n deps.logger,\n {\n repoUrl: repoUrl,\n includeCatalogInfoContent,\n },\n );\n\n if (!openImportPr?.prUrl) {\n const catalogLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations()\n ).uniqueCatalogUrlLocations.keys();\n\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n let exists = false;\n for (const loc of catalogLocations) {\n if (loc === catalogUrl) {\n exists = true;\n break;\n }\n }\n if (\n exists &&\n (await deps.gitApiService.hasFileInRepo({\n repoUrl,\n defaultBranch,\n fileName: getCatalogFilename(deps.config),\n }))\n ) {\n result.status = 'ADDED';\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n repoUrl,\n defaultBranch,\n );\n }\n // No import PR => let's determine last update from the repository\n const ghRepo =\n await deps.gitApiService.getRepositoryFromIntegrations(repoUrl);\n result.lastUpdate = ghRepo.repository?.updated_at ?? undefined;\n return {\n statusCode: 200,\n responseBody: result,\n };\n }\n result.status = 'WAIT_PR_APPROVAL';\n result[deps.approvalTool === 'GITLAB' ? 'gitlab' : 'github'] = {\n pullRequest: {\n number: openImportPr.prNum,\n url: openImportPr.prUrl,\n title: openImportPr.prTitle,\n body: openImportPr.prBody,\n catalogInfoContent: openImportPr.prCatalogInfoContent,\n },\n };\n\n result.lastUpdate = openImportPr.lastUpdate;\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n if (error.message?.includes('Not Found')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n result.status = 'PR_ERROR';\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nexport async function findTaskImportStatusByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n gitlabApiService: GitlabApiService;\n catalogHttpClient: CatalogHttpClient;\n repositoryDao: RepositoryDao<'repositories'>;\n taskDao: ScaffolderTaskDao;\n taskLocationsDao: TaskLocationsDao;\n discovery: DiscoveryService;\n auth: AuthService;\n },\n repoUrl: string,\n skipTasks?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(`Getting bulk import job status for ${repoUrl}.`);\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result: Components.Schemas.Import = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n },\n };\n try {\n const repository = await deps.repositoryDao.findRepositoryByUrl(repoUrl);\n if (!repository) {\n throw new NotFoundError(`Repository ${repoUrl} info was not found`);\n }\n\n const task = await deps.taskDao.lastExecutedTaskByRepoId(repository?.id);\n if (!task) {\n throw new NotFoundError(\n `Unable to find scaffolder task for repository: ${repository?.id}`,\n );\n }\n\n const scaffolderUrl = await deps.discovery.getBaseUrl('scaffolder');\n const { token } = await deps.auth.getPluginRequestToken({\n onBehalfOf: await deps.auth.getOwnServiceCredentials(),\n targetPluginId: 'scaffolder',\n });\n\n const response = await fetch(`${scaffolderUrl}/v2/tasks/${task.taskId}`, {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n if (!skipTasks) {\n const tasks = await deps.taskDao.findTasksByRepositoryId(repository.id);\n const tasksWithLocations = await Promise.all(\n tasks.map(async taskItem => {\n const locations = await deps.taskLocationsDao.findLocationsByTaskId(\n taskItem.taskId,\n );\n const taskLocations = locations.map(location => location.location);\n return {\n ...taskItem,\n locations: taskLocations,\n };\n }),\n );\n result.tasks = tasksWithLocations;\n }\n\n result.task = { taskId: task.taskId };\n let data;\n if (response.ok) {\n data = await response.json();\n result.lastUpdate = data.lastHeartbeatAt;\n\n const approvalTool =\n repository.approvalTool as unknown as Components.Schemas.ApprovalTool;\n const pullRequest = await parsePullOrMergeRequestInfo(\n data.state?.checkpoints,\n {\n githubApiService: deps.githubApiService,\n gitlabApiService: deps.gitlabApiService,\n approvalTool,\n logger: deps.logger,\n repoUrl,\n },\n );\n if (pullRequest && approvalTool === 'GITLAB') {\n result.gitlab = { pullRequest };\n }\n if (pullRequest && approvalTool === 'GIT') {\n result.github = { pullRequest };\n }\n\n result.status =\n `TASK_${(data.status as string)?.toLocaleUpperCase()}` as Components.Schemas.TaskImportStatus;\n } else {\n const errMsg =\n (await response.text()) ??\n `Failed to fetch task ${task.taskId}. Response status: ${response.status}`;\n throw new Error(errMsg);\n }\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n result.status = 'TASK_FETCH_FAILED';\n if (error.name?.includes('NotFoundError')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nexport async function findOrchestratorImportStatusByRepo(\n deps: {\n logger: LoggerService;\n orchestratorRepositoryDao: RepositoryDao<'orchestrator_repositories'>;\n orchestratorWorkflowDao: OrchestratorWorkflowDao;\n discovery: DiscoveryService;\n },\n repoUrl: string,\n token: string,\n skipWorkflows?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(\n `Getting orchestrator workflow import job status for ${repoUrl}.`,\n );\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result: Components.Schemas.Import = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n },\n };\n try {\n const repository =\n await deps.orchestratorRepositoryDao.findRepositoryByUrl(repoUrl);\n if (repository) {\n const workflow =\n await deps.orchestratorWorkflowDao.lastExecutedWorkflowByRepoId(\n repository.id,\n );\n if (!workflow) {\n throw new NotFoundError(\n `Workflow for repository ${repoUrl} was not found`,\n );\n }\n if (workflow.instanceId) {\n const baseUrl = await deps.discovery.getBaseUrl('orchestrator');\n const orchestratorApi = new DefaultApi(new Configuration(), baseUrl);\n const response = await orchestratorApi.getInstanceById(\n workflow.instanceId,\n {\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n },\n );\n\n const instance = response.data;\n if (instance) {\n result.workflow = {\n workflowId: instance.id,\n };\n if (!skipWorkflows) {\n const workflows =\n await deps.orchestratorWorkflowDao.findWorkflowsByRepositoryId(\n repository.id,\n );\n result.workflows = workflows.map((w: OrchestratorWorkflow) => ({\n workflowId: w.instanceId,\n }));\n }\n\n result.approvalTool =\n repository.approvalTool as unknown as Components.Schemas.ApprovalTool;\n result.lastUpdate = instance.end;\n const status =\n `WORKFLOW_${(instance.state as string)?.toLocaleUpperCase()}` as Components.Schemas.WorkflowImportStatus;\n result.status = status;\n }\n }\n }\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n result.status = 'WORKFLOW_FETCH_FAILED';\n if (error.name?.includes('NotFoundError')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nasync function parsePullOrMergeRequestInfo(\n checkpoints: Record<string, any>,\n {\n githubApiService,\n gitlabApiService,\n approvalTool,\n logger,\n repoUrl,\n }: {\n githubApiService: GithubApiService;\n gitlabApiService: GitlabApiService;\n approvalTool: Components.Schemas.ApprovalTool;\n logger: LoggerService;\n repoUrl: string;\n },\n): Promise<Components.Schemas.PullRequest | undefined> {\n // return errors ?\n if (approvalTool !== 'GITLAB' && approvalTool !== 'GIT') {\n return undefined;\n }\n const gitApiService =\n approvalTool === 'GITLAB' ? gitlabApiService : githubApiService;\n\n for (const key in checkpoints) {\n if (!checkpoints.hasOwnProperty(key)) {\n continue;\n }\n try {\n if (\n key.startsWith('v1.task.checkpoint.publish.create.pr') ||\n key.startsWith('v1.task.checkpoint.publish.create.mr')\n ) {\n const url =\n checkpoints[key]?.value?.html_url ??\n checkpoints[key]?.value?.mrWebUrl;\n if (!url) {\n continue;\n }\n const prNumber = Number.parseInt(url.split('/').pop()!, 10);\n const prDetails = await gitApiService.getPullRequest(repoUrl, prNumber);\n\n let catalogInfoContent: string | undefined;\n if (prDetails.prSha) {\n catalogInfoContent = await gitApiService.getCatalogInfoFile(logger, {\n repoUrl,\n prHeadSha: prDetails.prSha,\n prNumber,\n });\n }\n return {\n url,\n number: prNumber,\n title: prDetails.title,\n body: prDetails.body,\n status: prDetails.merged ? 'PR_MERGED' : 'WAIT_PR_APPROVAL',\n catalogInfoContent,\n };\n }\n } catch (err) {\n logger.warn(`Error while processing checkpoint ${key}: ${err}`);\n continue;\n }\n }\n\n return undefined;\n}\n\nexport async function deleteImportByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n gitApiService: GitApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n repoUrl: string,\n defaultBranch?: string,\n): Promise<HandlerResponse<void>> {\n deps.logger.debug(`Deleting bulk import job status for ${repoUrl}..`);\n\n // Check to see if there are any PR\n const openImportPr = await deps.gitApiService.findImportOpenPr(deps.logger, {\n repoUrl: repoUrl,\n });\n\n const gitUrl = gitUrlParse(repoUrl);\n if (openImportPr?.prUrl) {\n // Close PR\n const appTitle =\n deps.config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = deps.config.getString('app.baseUrl');\n\n await deps.gitApiService.closeImportPR(deps.logger, {\n repoUrl,\n gitUrl,\n comment: `Closing PR upon request for bulk import deletion. This request was created from [${appTitle}](${appBaseUrl}).`,\n });\n }\n // Also delete the import branch, so that it is not outdated if we try later to import the repo again\n await deps.gitApiService.deleteImportBranch({\n repoUrl,\n gitUrl,\n });\n // Remove Location from catalog\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n const findLocationFrom = (list: { id?: string; target: string }[]) => {\n for (const loc of list) {\n if (loc.target === catalogUrl) {\n return loc.id;\n }\n }\n return undefined;\n };\n\n const locationId = findLocationFrom(\n (\n await deps.catalogHttpClient.listCatalogUrlLocationsByIdFromLocationsEndpoint()\n ).locations,\n );\n if (locationId) {\n await deps.catalogHttpClient.deleteCatalogLocationById(locationId);\n }\n\n return {\n statusCode: 204,\n responseBody: undefined,\n };\n}\n\nexport async function deleteRepositoryRecord<\n DAO extends RepositoryDao<RepositoryName>,\n>(\n deps: {\n logger: LoggerService;\n dao: DAO;\n },\n repoUrl: string,\n): Promise<HandlerResponse<void>> {\n deps.logger.debug(`Deleting repository from database by name ${repoUrl}...`);\n try {\n await deps.dao.deleteRepository(repoUrl);\n\n return {\n statusCode: 204,\n responseBody: undefined,\n };\n } catch (error: any) {\n deps.logger.error(\n `Failed to delete repository from database by url ${repoUrl}`,\n error,\n );\n return {\n statusCode: 500,\n };\n }\n}\n"],"names":["DefaultSortColumn","DefaultSortOrder","getNestedValue","DefaultPageNumber","DefaultPageSize","getCatalogFilename","parseGitURLForApprovalTool","imports","paginateArray","logErrorIfNeeded","getCatalogUrl","gitUrlParse","errors","NotFoundError","DefaultApi","Configuration"],"mappings":";;;;;;;;;;;;;;;;;;AAwEO,SAAS,WAAA,CACd,OAAA,EACA,UAAA,GAAyDA,0BAAA,EACzD,YAAuDC,yBAAA,EACvD;AACA,EAAA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM;AACrB,IAAA,MAAM,MAAA,GAASC,oBAAA,CAAe,CAAA,EAAG,UAAU,CAAA;AAC3C,IAAA,MAAM,MAAA,GAASA,oBAAA,CAAe,CAAA,EAAG,UAAU,CAAA;AAE3C,IAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,MAAA,EAAW,OAAO,CAAA;AACzD,IAAA,IAAI,MAAA,KAAW,MAAA,EAAW,OAAO,SAAA,KAAc,QAAQ,EAAA,GAAK,CAAA;AAC5D,IAAA,IAAI,MAAA,KAAW,MAAA,EAAW,OAAO,SAAA,KAAc,QAAQ,CAAA,GAAI,EAAA;AAE3D,IAAA,IAAI,eAAe,YAAA,EAAc;AAC/B,MAAA,MAAM,KAAA,GAAQ,IAAI,IAAA,CAAK,MAAM,CAAA;AAC7B,MAAA,MAAM,KAAA,GAAQ,IAAI,IAAA,CAAK,MAAM,CAAA;AAE7B,MAAA,OAAO,SAAA,KAAc,KAAA,GACjB,KAAA,CAAM,OAAA,EAAQ,GAAI,KAAA,CAAM,OAAA,EAAQ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,OAAO,CAAA,GAAA,CAAK,CAAA;AAC3E,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,CAAK,GAAA,CAAI,gBAAA,CAAiB,OAAO,CAAA;AAEvC,IAAA,OAAO;AAAA,MACL,UAAA,EAAY,GAAA;AAAA,MACZ,YAAA,EAAc,KAAA;AAAA,KAChB;AAAA,EACF,SAAS,KAAA,EAAY;AACnB,IAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,MACV,oDAAoD,OAAO,CAAA,CAAA;AAAA,MAC3D;AAAA,KACF;AACA,IAAA,OAAO;AAAA,MACL,UAAA,EAAY;AAAA,KACd;AAAA,EACF;AACF;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"bulkImports.cjs.js","sources":["../../../../src/service/handlers/import/bulkImports.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AuthService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport { NotFoundError } from '@backstage/errors';\n\nimport type { Request } from 'express';\nimport gitUrlParse from 'git-url-parse';\n\nimport {\n Configuration,\n DefaultApi,\n} from '@red-hat-developer-hub/backstage-plugin-orchestrator-common';\n\nimport { CatalogHttpClient } from '../../../catalog/catalogHttpClient';\nimport type { CatalogInfoGenerator } from '../../../catalog/catalogInfoGenerator';\nimport {\n getCatalogFilename,\n getCatalogUrl,\n} from '../../../catalog/catalogUtils';\nimport {\n OrchestratorWorkflow,\n OrchestratorWorkflowDao,\n RepositoryDao,\n RepositoryName,\n ScaffolderTaskDao,\n TaskLocationsDao,\n} from '../../../database/repositoryDao';\nimport type { Components, Paths } from '../../../generated/openapi';\nimport type { GithubApiService } from '../../../github';\nimport { GitlabApiService } from '../../../gitlab';\nimport {\n getNestedValue,\n logErrorIfNeeded,\n paginateArray,\n parseGitURLForApprovalTool,\n} from '../../../helpers';\nimport { GitApiService } from '../../../scm/GitApiService';\nimport {\n DefaultPageNumber,\n DefaultPageSize,\n DefaultSortColumn,\n DefaultSortOrder,\n type HandlerResponse,\n} from '../handlers';\n\ntype CreateImportDryRunStatus =\n | 'CATALOG_ENTITY_CONFLICT'\n | 'CATALOG_INFO_FILE_EXISTS_IN_REPO'\n | 'CODEOWNERS_FILE_NOT_FOUND_IN_REPO'\n | 'REPO_EMPTY';\n\ntype FindAllImportsResponse =\n Components.Schemas.Import[] | Components.Schemas.ImportJobListV2;\n\nexport function sortImports(\n imports: Components.Schemas.Import[],\n sortColumn: Components.Parameters.SortColumnQueryParam = DefaultSortColumn,\n sortOrder: Components.Parameters.SortOrderQueryParam = DefaultSortOrder,\n) {\n imports.sort((a, b) => {\n const value1 = getNestedValue(a, sortColumn);\n const value2 = getNestedValue(b, sortColumn);\n // Handle cases where values are undefined\n if (value1 === undefined && value2 === undefined) return 0;\n if (value1 === undefined) return sortOrder === 'asc' ? -1 : 1;\n if (value2 === undefined) return sortOrder === 'asc' ? 1 : -1;\n\n if (sortColumn === 'lastUpdate') {\n const date1 = new Date(value1); // Convert string to Date object\n const date2 = new Date(value2); // Convert string to Date object\n // Compare dates\n return sortOrder === 'asc'\n ? date2.getTime() - date1.getTime()\n : date1.getTime() - date2.getTime();\n }\n // Compare values based on sort order\n return sortOrder === 'asc'\n ? value1.localeCompare(value2)\n : value2.localeCompare(value1);\n });\n}\n\nexport async function findAllImports(\n deps: {\n logger: LoggerService;\n config: Config;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n requestHeaders?: {\n apiVersion?: Paths.FindAllImports.Parameters.ApiVersion;\n },\n queryParams?: {\n search?: string;\n pageNumber?: number;\n pageSize?: number;\n sortColumn?: Components.Parameters.SortColumnQueryParam;\n sortOrder?: Components.Parameters.SortOrderQueryParam;\n },\n): Promise<HandlerResponse<FindAllImportsResponse>> {\n const apiVersion = requestHeaders?.apiVersion ?? 'v1';\n const search = queryParams?.search;\n const pageNumber = queryParams?.pageNumber ?? DefaultPageNumber;\n const pageSize = queryParams?.pageSize ?? DefaultPageSize;\n const sortColumn = queryParams?.sortColumn ?? DefaultSortColumn;\n const sortOrder = queryParams?.sortOrder ?? DefaultSortOrder;\n\n const catalogFilename = getCatalogFilename(deps.config);\n\n const allLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations(\n search,\n pageNumber,\n pageSize,\n )\n ).uniqueCatalogUrlLocations;\n\n // resolve default branches for each unique repo URL from GH,\n // because we cannot easily determine that from the location target URL.\n // It can be 'main' or something more convoluted like 'our/awesome/main'.\n const defaultBranchByRepoUrl = await resolveReposDefaultBranches(\n deps.logger,\n deps.gitlabApiService,\n deps.githubApiService,\n allLocations.keys(),\n catalogFilename,\n );\n\n // filter out locations that do not match what we are expecting, i.e.:\n // an URL to a catalog-info YAML file at the root of the repo\n const importCandidates = findImportCandidates(\n allLocations.keys(),\n defaultBranchByRepoUrl,\n catalogFilename,\n );\n\n // Keep only repos that are accessible from the configured GH/GL integrations\n const importsReachableFromGHIntegrations =\n await deps.githubApiService.filterLocationsAccessibleFromIntegrations(\n importCandidates.filter(val => {\n return parseGitURLForApprovalTool(val) === 'GIT';\n }),\n );\n\n const importsReachableFromGLIntegrations =\n await deps.gitlabApiService.filterLocationsAccessibleFromIntegrations(\n importCandidates.filter(val => {\n return parseGitURLForApprovalTool(val) === 'GITLAB';\n }),\n );\n\n // Merge the two lists together and map the appropriate approvalTool\n const mergedReachbleFromIntegrations = importsReachableFromGHIntegrations\n .map(val => {\n return {\n loc: val,\n approvalTool: 'GIT',\n };\n })\n .concat(\n importsReachableFromGLIntegrations.map(val => {\n return {\n loc: val,\n approvalTool: 'GITLAB',\n };\n }),\n );\n\n const repoUrlToLocation = new Map<string, string>();\n\n // now fetch the import statuses in different promises\n const importStatusPromises: Promise<\n HandlerResponse<Components.Schemas.Import>\n >[] = [];\n for (const imports of mergedReachbleFromIntegrations) {\n const repoUrl = repoUrlFromLocation(imports.loc);\n if (!repoUrl) {\n continue;\n }\n repoUrlToLocation.set(repoUrl, imports.loc);\n\n importStatusPromises.push(\n findImportStatusByRepo(\n {\n logger: deps.logger,\n config: deps.config,\n gitApiService:\n imports.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService,\n catalogHttpClient: deps.catalogHttpClient,\n approvalTool: imports.approvalTool,\n },\n repoUrl,\n defaultBranchByRepoUrl.get(repoUrl),\n false,\n ),\n );\n }\n\n const result = await Promise.all(importStatusPromises);\n const imports = result\n .filter(res => res.responseBody)\n .map(res => res.responseBody!)\n .map(res => {\n const key = res?.repository?.url;\n const location = key ? repoUrlToLocation.get(key) : undefined;\n return {\n ...res,\n source: location ? allLocations.get(location)?.source : undefined,\n };\n });\n\n // sorting the output to make it deterministic and easy to navigate in the UI\n\n sortImports(imports, sortColumn, sortOrder);\n const paginated = paginateArray(imports, pageNumber, pageSize);\n if (apiVersion === 'v1') {\n return {\n statusCode: 200,\n responseBody: paginated.result,\n };\n }\n return {\n statusCode: 200,\n responseBody: {\n imports: paginated.result,\n totalCount: paginated.totalCount,\n page: pageNumber,\n size: pageSize,\n },\n };\n}\n\nasync function resolveReposDefaultBranches(\n logger: LoggerService,\n gitlabApiService: GitlabApiService,\n githubApiService: GithubApiService,\n allLocations: Iterable<string>,\n catalogFilename: string,\n) {\n const defaultBranchByRepoUrlPromises: Promise<{\n repoUrl: string;\n defaultBranch?: string;\n }>[] = [];\n for (const loc of allLocations) {\n // loc has the following format: https://github.com/<org>/<repo>/blob/<default-branch>/catalog-info.yaml\n // but it can have a more convoluted format like 'https://github.com/redhat-developer/rhdh-plugins/blob/main/plugins/scaffolder-annotator-action/examples/templates/01-scaffolder-template.yaml'\n // if registered manually from the 'Register existing component' feature in Backstage.\n if (!loc.endsWith(catalogFilename)) {\n logger.debug(\n `Ignored location ${loc} because it does not point to a file named ${catalogFilename}`,\n );\n continue;\n }\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n // Have to do this for Both the gitlab/github, possibly a better way?\n // Should probably parse the URL to figure out which to use?\n defaultBranchByRepoUrlPromises.push(\n (parseGitURLForApprovalTool(repoUrl) === 'GITLAB'\n ? gitlabApiService\n : githubApiService\n )\n .getRepositoryFromIntegrations(repoUrl)\n .then(resp => {\n return { repoUrl, defaultBranch: resp?.repository?.default_branch };\n })\n .catch((err: any) => {\n logErrorIfNeeded(\n logger,\n `Ignored repo ${repoUrl} due to an error while fetching details from GitHub`,\n err,\n );\n return {\n repoUrl,\n defaultBranch: undefined,\n };\n }),\n );\n }\n const defaultBranchesResponses = await Promise.all(\n defaultBranchByRepoUrlPromises,\n );\n return new Map(\n defaultBranchesResponses\n .flat()\n .filter(r => r.defaultBranch)\n .map(r => [r.repoUrl, r.defaultBranch!]),\n );\n}\n\nfunction repoUrlFromLocation(loc: string) {\n const split = loc.split('/blob/');\n if (split.length < 2) {\n return undefined;\n }\n return split[0];\n}\n\nfunction findImportCandidates(\n allLocations: Iterable<string>,\n defaultBranchByRepoUrl: Map<string, string>,\n catalogFilename: string,\n) {\n const filteredLocations: string[] = [];\n for (const loc of allLocations) {\n const repoUrl = repoUrlFromLocation(loc);\n if (!repoUrl) {\n continue;\n }\n\n const defaultBranch = defaultBranchByRepoUrl.get(repoUrl);\n if (!defaultBranch) {\n continue;\n }\n if (loc !== `${repoUrl}/blob/${defaultBranch}/${catalogFilename}`) {\n // Because users can use the \"Register existing component\" workflow to register a Location\n // using any file path in the repo, we consider a repository as an Import Location only\n // if it is at the root of the repository, because that is what the import PR ultimately does.\n continue;\n }\n filteredLocations.push(loc);\n }\n return filteredLocations;\n}\n\nasync function createPR(\n gitApiService: GitApiService,\n logger: LoggerService,\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n catalogInfoGenerator: CatalogInfoGenerator,\n config: Config,\n) {\n const appTitle =\n config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = config.getString('app.baseUrl');\n const catalogFileName = getCatalogFilename(config);\n return await gitApiService.submitPrToRepo(logger, {\n repoUrl: req.repository.url,\n gitUrl: gitUrl,\n defaultBranch: req.repository.defaultBranch,\n catalogInfoContent:\n req.catalogInfoContent ??\n (await catalogInfoGenerator.generateDefaultCatalogInfoContent(\n req.repository.url,\n )),\n prTitle:\n req[req.approvalTool === 'GITLAB' ? 'gitlab' : 'github']?.pullRequest\n ?.title ?? `Add ${catalogFileName}`,\n prBody:\n req[req.approvalTool === 'GITLAB' ? 'gitlab' : 'github']?.pullRequest\n ?.body ??\n `\nThis pull request adds a **Backstage entity metadata file** to this repository so that the component can be added to a Backstage application.\n\nAfter this pull request is merged, the component will become available in the [${appTitle} software catalog](${appBaseUrl}).\n\nFor more information, read an [overview of the Backstage software catalog](https://backstage.io/docs/features/software-catalog/).\n`,\n });\n}\n\nasync function handleAddedReposFromCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Components.Schemas.ImportRequest[],\n) {\n const result: Components.Schemas.Import[] = [];\n\n for (const req of importRequests) {\n // Check if repo is already imported\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const hasLocation =\n await deps.catalogHttpClient.verifyLocationExistence(repoCatalogUrl);\n if (!hasLocation) {\n continue;\n }\n const gitApiService =\n req.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService;\n const hasCatalogInfoFileInRepo = await gitApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (!hasCatalogInfoFileInRepo) {\n continue;\n }\n\n const ghRepo = await gitApiService.getRepositoryFromIntegrations(\n req.repository.url,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n\n const gitUrl = gitUrlParse(req.repository.url);\n result.push({\n status: 'ADDED',\n lastUpdate: ghRepo?.repository?.updated_at ?? undefined,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function handlePrCreationRequest(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n gitUrl: gitUrlParse.GitUrl,\n): Promise<Components.Schemas.Import> {\n const repoCatalogUrl = getCatalogUrl(\n deps.config,\n req.repository.url,\n req.repository.defaultBranch,\n );\n const gitApiService =\n req.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService;\n const prToRepo = await createPR(\n gitApiService,\n deps.logger,\n req,\n gitUrl,\n deps.catalogInfoGenerator,\n deps.config,\n );\n if (prToRepo.errors && prToRepo.errors.length > 0) {\n return {\n errors: prToRepo.errors,\n status: 'PR_ERROR',\n repository: req.repository,\n };\n }\n if (prToRepo.prUrl) {\n deps.logger.debug(`Created new PR from request: ${prToRepo.prUrl}`);\n }\n\n // Create Location\n await deps.catalogHttpClient.possiblyCreateLocation(repoCatalogUrl);\n\n if (prToRepo.hasChanges === false) {\n deps.logger.debug(\n `No bulk import PR created on ${req.repository.url} since its default branch (${req.repository.defaultBranch}) already contains a catalog-info file`,\n );\n\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n req.repository.url,\n req.repository.defaultBranch,\n );\n return {\n status: 'ADDED',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n };\n }\n\n return {\n approvalTool: req.approvalTool ?? 'GIT',\n errors: prToRepo.errors,\n status: 'WAIT_PR_APPROVAL',\n lastUpdate: prToRepo.lastUpdate,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n [req.approvalTool === 'GITLAB' ? 'gitlab' : 'github']: {\n pullRequest: {\n url: prToRepo.prUrl,\n number: prToRepo.prNumber,\n },\n },\n };\n}\n\nexport async function createImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n reqParams: {\n importRequests: Paths.CreateImportJobs.RequestBody;\n dryRun?: boolean;\n },\n): Promise<HandlerResponse<Components.Schemas.Import[]>> {\n const dryRun = reqParams.dryRun ?? false;\n const importRequests = reqParams.importRequests;\n deps.logger.debug(\n `Handling request to import ${importRequests?.length} repo(s) (dryRun=${dryRun})..`,\n );\n\n if (importRequests.length === 0) {\n deps.logger.debug('Missing import requests from request body');\n return {\n statusCode: 400,\n responseBody: [],\n };\n }\n\n if (dryRun) {\n return {\n statusCode: 202,\n responseBody: await dryRunCreateImportJobs(deps, importRequests),\n };\n }\n\n const result: Components.Schemas.Import[] = [];\n\n const addedRepos = await handleAddedReposFromCreateImportJobs(\n deps,\n importRequests,\n );\n result.push(...addedRepos);\n const addedReposMap = new Map(\n addedRepos.map(res => [res.repository?.url, res]),\n );\n const remainingRequests = importRequests.filter(\n req => !addedReposMap.has(req.repository.url),\n );\n\n for (const req of remainingRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n // Create PR\n try {\n result.push(await handlePrCreationRequest(deps, req, gitUrl));\n } catch (error: any) {\n result.push({\n errors: [error.message],\n status: 'PR_ERROR',\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n } as Components.Schemas.Import);\n }\n }\n\n sortImports(result);\n\n return {\n statusCode: 202,\n responseBody: result,\n };\n}\n\nasync function dryRunCreateImportJobs(\n deps: {\n logger: LoggerService;\n config: Config;\n auth: AuthService;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogInfoGenerator: CatalogInfoGenerator;\n catalogHttpClient: CatalogHttpClient;\n },\n importRequests: Paths.CreateImportJobs.RequestBody,\n) {\n const result: Components.Schemas.Import[] = [];\n for (const req of importRequests) {\n const gitUrl = gitUrlParse(req.repository.url);\n\n const dryRunChecks = await performDryRunChecks(deps, req);\n if (dryRunChecks.errors?.length > 0) {\n deps.logger.warn(\n `Errors while performing dry-run checks: ${dryRunChecks.errors}`,\n );\n }\n result.push({\n errors: dryRunChecks.dryRunStatuses,\n catalogEntityName: req.catalogEntityName,\n repository: {\n url: req.repository.url,\n name: gitUrl.name,\n organization: gitUrl.organization,\n },\n });\n }\n return result;\n}\n\nasync function performDryRunChecks(\n deps: {\n logger: LoggerService;\n auth: AuthService;\n config: Config;\n gitlabApiService: GitlabApiService;\n githubApiService: GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n req: Components.Schemas.ImportRequest,\n): Promise<{ dryRunStatuses: CreateImportDryRunStatus[]; errors: string[] }> {\n const checkCatalog = async (\n catalogEntityName: string,\n ): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const hasEntity =\n await deps.catalogHttpClient.hasEntityInCatalog(catalogEntityName);\n if (hasEntity) {\n return { dryRunStatuses: ['CATALOG_ENTITY_CONFLICT'] };\n }\n return {};\n };\n\n const gitApiService =\n req.approvalTool === 'GITLAB'\n ? deps.gitlabApiService\n : deps.githubApiService;\n const checkEmptyRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const empty = await gitApiService.isRepoEmpty({\n repoUrl: req.repository.url,\n });\n if (empty) {\n return {\n dryRunStatuses: ['REPO_EMPTY'],\n };\n }\n return {};\n };\n\n const checkCatalogInfoPresenceInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const exists = await gitApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: getCatalogFilename(deps.config),\n });\n if (exists) {\n return {\n dryRunStatuses: ['CATALOG_INFO_FILE_EXISTS_IN_REPO'],\n };\n }\n return {};\n };\n\n const checkCodeOwnersFileInRepo = async (): Promise<{\n dryRunStatuses?: CreateImportDryRunStatus[];\n errors?: string[];\n }> => {\n const gitDirLocation =\n req.approvalTool === 'GITLAB' ? '.gitlab' : '.github';\n const exists = await gitApiService.hasFileInRepo({\n repoUrl: req.repository.url,\n defaultBranch: req.repository.defaultBranch,\n fileName: `${gitDirLocation}/CODEOWNERS`,\n });\n if (!exists) {\n return {\n dryRunStatuses: ['CODEOWNERS_FILE_NOT_FOUND_IN_REPO'],\n };\n }\n return {};\n };\n\n const dryRunStatuses: CreateImportDryRunStatus[] = [];\n const errors: string[] = [];\n const allChecksFn = [checkEmptyRepo(), checkCatalogInfoPresenceInRepo()];\n if (req.catalogEntityName?.trim()) {\n allChecksFn.push(checkCatalog(req.catalogEntityName));\n }\n if (req.codeOwnersFileAsEntityOwner) {\n allChecksFn.push(checkCodeOwnersFileInRepo());\n }\n const allChecks = await Promise.all(allChecksFn);\n allChecks.flat().forEach(res => {\n if (res.dryRunStatuses) {\n dryRunStatuses.push(...res.dryRunStatuses);\n }\n if (res.errors) {\n errors.push(...res.errors);\n }\n });\n\n dryRunStatuses.sort((a, b) => a.localeCompare(b));\n\n return {\n dryRunStatuses,\n errors,\n };\n}\n\nexport async function findImportStatusByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n gitApiService: GitlabApiService | GithubApiService;\n catalogHttpClient: CatalogHttpClient;\n approvalTool: string | undefined;\n },\n repoUrl: string,\n defaultBranch?: string,\n includeCatalogInfoContent?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(`Getting bulk import job status for ${repoUrl}..`);\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n defaultBranch,\n },\n approvalTool: deps.approvalTool,\n status: null,\n } as Components.Schemas.Import;\n try {\n // Check to see if there are any PR\n const openImportPr = await deps.gitApiService.findImportOpenPr(\n deps.logger,\n {\n repoUrl: repoUrl,\n includeCatalogInfoContent,\n },\n );\n\n if (!openImportPr?.prUrl) {\n const catalogLocations = (\n await deps.catalogHttpClient.listCatalogUrlLocations()\n ).uniqueCatalogUrlLocations.keys();\n\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n let exists = false;\n for (const loc of catalogLocations) {\n if (loc === catalogUrl) {\n exists = true;\n break;\n }\n }\n if (\n exists &&\n (await deps.gitApiService.hasFileInRepo({\n repoUrl,\n defaultBranch,\n fileName: getCatalogFilename(deps.config),\n }))\n ) {\n result.status = 'ADDED';\n // Force a refresh of the Location, so that the entities from the catalog-info.yaml can show up quickly (not guaranteed however).\n await deps.catalogHttpClient.refreshLocationByRepoUrl(\n repoUrl,\n defaultBranch,\n );\n }\n // No import PR => let's determine last update from the repository\n const ghRepo =\n await deps.gitApiService.getRepositoryFromIntegrations(repoUrl);\n result.lastUpdate = ghRepo.repository?.updated_at ?? undefined;\n return {\n statusCode: 200,\n responseBody: result,\n };\n }\n result.status = 'WAIT_PR_APPROVAL';\n result[deps.approvalTool === 'GITLAB' ? 'gitlab' : 'github'] = {\n pullRequest: {\n number: openImportPr.prNum,\n url: openImportPr.prUrl,\n title: openImportPr.prTitle,\n body: openImportPr.prBody,\n catalogInfoContent: openImportPr.prCatalogInfoContent,\n },\n };\n\n result.lastUpdate = openImportPr.lastUpdate;\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n if (error.message?.includes('Not Found')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n result.status = 'PR_ERROR';\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nexport async function findTaskImportStatusByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n githubApiService: GithubApiService;\n gitlabApiService: GitlabApiService;\n catalogHttpClient: CatalogHttpClient;\n repositoryDao: RepositoryDao<'repositories'>;\n taskDao: ScaffolderTaskDao;\n taskLocationsDao: TaskLocationsDao;\n discovery: DiscoveryService;\n auth: AuthService;\n },\n repoUrl: string,\n skipTasks?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(`Getting bulk import job status for ${repoUrl}.`);\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result: Components.Schemas.Import = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n },\n };\n try {\n const repository = await deps.repositoryDao.findRepositoryByUrl(repoUrl);\n if (!repository) {\n throw new NotFoundError(`Repository ${repoUrl} info was not found`);\n }\n\n const task = await deps.taskDao.lastExecutedTaskByRepoId(repository?.id);\n if (!task) {\n throw new NotFoundError(\n `Unable to find scaffolder task for repository: ${repository?.id}`,\n );\n }\n\n const scaffolderUrl = await deps.discovery.getBaseUrl('scaffolder');\n const { token } = await deps.auth.getPluginRequestToken({\n onBehalfOf: await deps.auth.getOwnServiceCredentials(),\n targetPluginId: 'scaffolder',\n });\n\n const response = await fetch(`${scaffolderUrl}/v2/tasks/${task.taskId}`, {\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n if (!skipTasks) {\n const tasks = await deps.taskDao.findTasksByRepositoryId(repository.id);\n const tasksWithLocations = await Promise.all(\n tasks.map(async taskItem => {\n const locations = await deps.taskLocationsDao.findLocationsByTaskId(\n taskItem.taskId,\n );\n const taskLocations = locations.map(location => location.location);\n return {\n ...taskItem,\n locations: taskLocations,\n };\n }),\n );\n result.tasks = tasksWithLocations;\n }\n\n result.task = { taskId: task.taskId };\n let data;\n if (response.ok) {\n data = await response.json();\n result.lastUpdate = data.lastHeartbeatAt;\n\n const approvalTool =\n repository.approvalTool as unknown as Components.Schemas.ApprovalTool;\n const pullRequest = await parsePullOrMergeRequestInfo(\n data.state?.checkpoints,\n {\n githubApiService: deps.githubApiService,\n gitlabApiService: deps.gitlabApiService,\n approvalTool,\n logger: deps.logger,\n repoUrl,\n },\n );\n if (pullRequest && approvalTool === 'GITLAB') {\n result.gitlab = { pullRequest };\n }\n if (pullRequest && approvalTool === 'GIT') {\n result.github = { pullRequest };\n }\n\n result.status =\n `TASK_${(data.status as string)?.toLocaleUpperCase()}` as Components.Schemas.TaskImportStatus;\n } else {\n const errMsg =\n (await response.text()) ??\n `Failed to fetch task ${task.taskId}. Response status: ${response.status}`;\n throw new Error(errMsg);\n }\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n result.status = 'TASK_FETCH_FAILED';\n if (error.name?.includes('NotFoundError')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nexport async function findOrchestratorImportStatusByRepo(\n deps: {\n logger: LoggerService;\n orchestratorRepositoryDao: RepositoryDao<'orchestrator_repositories'>;\n orchestratorWorkflowDao: OrchestratorWorkflowDao;\n discovery: DiscoveryService;\n auth: AuthService;\n httpAuth: HttpAuthService;\n req: Request;\n },\n repoUrl: string,\n skipWorkflows?: boolean,\n): Promise<HandlerResponse<Components.Schemas.Import>> {\n deps.logger.debug(\n `Getting orchestrator workflow import job status for ${repoUrl}.`,\n );\n\n const gitUrl = gitUrlParse(repoUrl);\n\n const errors: string[] = [];\n const result: Components.Schemas.Import = {\n id: repoUrl,\n repository: {\n url: repoUrl,\n name: gitUrl.name,\n organization: gitUrl.organization,\n id: `${gitUrl.organization}/${gitUrl.name}`,\n },\n };\n try {\n const repository =\n await deps.orchestratorRepositoryDao.findRepositoryByUrl(repoUrl);\n if (repository) {\n const workflow =\n await deps.orchestratorWorkflowDao.lastExecutedWorkflowByRepoId(\n repository.id,\n );\n if (!workflow) {\n throw new NotFoundError(\n `Workflow for repository ${repoUrl} was not found`,\n );\n }\n if (workflow.instanceId) {\n const baseUrl = await deps.discovery.getBaseUrl('orchestrator');\n const { token } = await deps.auth.getPluginRequestToken({\n onBehalfOf: await deps.httpAuth.credentials(deps.req),\n targetPluginId: 'orchestrator',\n });\n const orchestratorApi = new DefaultApi(new Configuration(), baseUrl);\n const response = await orchestratorApi.getInstanceById(\n workflow.instanceId,\n {\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n },\n );\n\n const instance = response.data;\n if (instance) {\n result.workflow = {\n workflowId: instance.id,\n };\n if (!skipWorkflows) {\n const workflows =\n await deps.orchestratorWorkflowDao.findWorkflowsByRepositoryId(\n repository.id,\n );\n result.workflows = workflows.map((w: OrchestratorWorkflow) => ({\n workflowId: w.instanceId,\n }));\n }\n\n result.approvalTool =\n repository.approvalTool as unknown as Components.Schemas.ApprovalTool;\n result.lastUpdate = instance.end;\n const status =\n `WORKFLOW_${(instance.state as string)?.toLocaleUpperCase()}` as Components.Schemas.WorkflowImportStatus;\n result.status = status;\n }\n }\n }\n } catch (error: any) {\n errors.push(error.message);\n result.errors = errors;\n result.status = 'WORKFLOW_FETCH_FAILED';\n if (error.name?.includes('NotFoundError')) {\n return {\n statusCode: 404,\n responseBody: result,\n };\n }\n }\n\n return {\n statusCode: 200,\n responseBody: result,\n };\n}\n\nasync function parsePullOrMergeRequestInfo(\n checkpoints: Record<string, any>,\n {\n githubApiService,\n gitlabApiService,\n approvalTool,\n logger,\n repoUrl,\n }: {\n githubApiService: GithubApiService;\n gitlabApiService: GitlabApiService;\n approvalTool: Components.Schemas.ApprovalTool;\n logger: LoggerService;\n repoUrl: string;\n },\n): Promise<Components.Schemas.PullRequest | undefined> {\n // return errors ?\n if (approvalTool !== 'GITLAB' && approvalTool !== 'GIT') {\n return undefined;\n }\n const gitApiService =\n approvalTool === 'GITLAB' ? gitlabApiService : githubApiService;\n\n for (const key in checkpoints) {\n if (!checkpoints.hasOwnProperty(key)) {\n continue;\n }\n try {\n if (\n key.startsWith('v1.task.checkpoint.publish.create.pr') ||\n key.startsWith('v1.task.checkpoint.publish.create.mr')\n ) {\n const url =\n checkpoints[key]?.value?.html_url ??\n checkpoints[key]?.value?.mrWebUrl;\n if (!url) {\n continue;\n }\n const prNumber = Number.parseInt(url.split('/').pop()!, 10);\n const prDetails = await gitApiService.getPullRequest(repoUrl, prNumber);\n\n let catalogInfoContent: string | undefined;\n if (prDetails.prSha) {\n catalogInfoContent = await gitApiService.getCatalogInfoFile(logger, {\n repoUrl,\n prHeadSha: prDetails.prSha,\n prNumber,\n });\n }\n return {\n url,\n number: prNumber,\n title: prDetails.title,\n body: prDetails.body,\n status: prDetails.merged ? 'PR_MERGED' : 'WAIT_PR_APPROVAL',\n catalogInfoContent,\n };\n }\n } catch (err) {\n logger.warn(`Error while processing checkpoint ${key}: ${err}`);\n continue;\n }\n }\n\n return undefined;\n}\n\nexport async function deleteImportByRepo(\n deps: {\n logger: LoggerService;\n config: Config;\n gitApiService: GitApiService;\n catalogHttpClient: CatalogHttpClient;\n },\n repoUrl: string,\n defaultBranch?: string,\n): Promise<HandlerResponse<void>> {\n deps.logger.debug(`Deleting bulk import job status for ${repoUrl}..`);\n\n // Check to see if there are any PR\n const openImportPr = await deps.gitApiService.findImportOpenPr(deps.logger, {\n repoUrl: repoUrl,\n });\n\n const gitUrl = gitUrlParse(repoUrl);\n if (openImportPr?.prUrl) {\n // Close PR\n const appTitle =\n deps.config.getOptionalString('app.title') ?? 'Red Hat Developer Hub';\n const appBaseUrl = deps.config.getString('app.baseUrl');\n\n await deps.gitApiService.closeImportPR(deps.logger, {\n repoUrl,\n gitUrl,\n comment: `Closing PR upon request for bulk import deletion. This request was created from [${appTitle}](${appBaseUrl}).`,\n });\n }\n // Also delete the import branch, so that it is not outdated if we try later to import the repo again\n await deps.gitApiService.deleteImportBranch({\n repoUrl,\n gitUrl,\n });\n // Remove Location from catalog\n const catalogUrl = getCatalogUrl(deps.config, repoUrl, defaultBranch);\n const findLocationFrom = (list: { id?: string; target: string }[]) => {\n for (const loc of list) {\n if (loc.target === catalogUrl) {\n return loc.id;\n }\n }\n return undefined;\n };\n\n const locationId = findLocationFrom(\n (\n await deps.catalogHttpClient.listCatalogUrlLocationsByIdFromLocationsEndpoint()\n ).locations,\n );\n if (locationId) {\n await deps.catalogHttpClient.deleteCatalogLocationById(locationId);\n }\n\n return {\n statusCode: 204,\n responseBody: undefined,\n };\n}\n\nexport async function deleteRepositoryRecord<\n DAO extends RepositoryDao<RepositoryName>,\n>(\n deps: {\n logger: LoggerService;\n dao: DAO;\n },\n repoUrl: string,\n): Promise<HandlerResponse<void>> {\n deps.logger.debug(`Deleting repository from database by name ${repoUrl}...`);\n try {\n await deps.dao.deleteRepository(repoUrl);\n\n return {\n statusCode: 204,\n responseBody: undefined,\n };\n } catch (error: any) {\n deps.logger.error(\n `Failed to delete repository from database by url ${repoUrl}`,\n error,\n );\n return {\n statusCode: 500,\n };\n }\n}\n"],"names":["DefaultSortColumn","DefaultSortOrder","getNestedValue","DefaultPageNumber","DefaultPageSize","getCatalogFilename","parseGitURLForApprovalTool","imports","paginateArray","logErrorIfNeeded","getCatalogUrl","gitUrlParse","errors","NotFoundError","DefaultApi","Configuration"],"mappings":";;;;;;;;;;;;;;;;;;AA0EO,SAAS,WAAA,CACd,OAAA,EACA,UAAA,GAAyDA,0BAAA,EACzD,YAAuDC,yBAAA,EACvD;AACA,EAAA,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,K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;AAAA,EACF;AACF;;;;;;;;;;;"}
|
|
@@ -7,7 +7,9 @@ async function createWorkflowImportJobs(args) {
|
|
|
7
7
|
const {
|
|
8
8
|
orchestratorWorkflowId,
|
|
9
9
|
discovery,
|
|
10
|
-
|
|
10
|
+
auth,
|
|
11
|
+
httpAuth,
|
|
12
|
+
req,
|
|
11
13
|
requestBody,
|
|
12
14
|
orchestratorWorkflowDao,
|
|
13
15
|
orchestratorRepositoryDao,
|
|
@@ -22,6 +24,10 @@ async function createWorkflowImportJobs(args) {
|
|
|
22
24
|
}
|
|
23
25
|
const result = [];
|
|
24
26
|
const baseUrl = await discovery.getBaseUrl("orchestrator");
|
|
27
|
+
const { token } = await auth.getPluginRequestToken({
|
|
28
|
+
onBehalfOf: await httpAuth.credentials(req),
|
|
29
|
+
targetPluginId: "orchestrator"
|
|
30
|
+
});
|
|
25
31
|
const apiConfig = new backstagePluginOrchestratorCommon.Configuration();
|
|
26
32
|
const orchestratorApi = new backstagePluginOrchestratorCommon.DefaultApi(apiConfig, baseUrl);
|
|
27
33
|
for (const repo of requestBody) {
|
|
@@ -33,7 +39,7 @@ async function createWorkflowImportJobs(args) {
|
|
|
33
39
|
const approvalTool = repo.approvalTool ?? "GIT";
|
|
34
40
|
const authTokens = [];
|
|
35
41
|
if (approvalTool === "GIT") {
|
|
36
|
-
const creds = await githubApiService.
|
|
42
|
+
const creds = await githubApiService.getAppInstallationCredentials(
|
|
37
43
|
repo.repository.url
|
|
38
44
|
);
|
|
39
45
|
authTokens.push({ token: creds?.token, provider: "github" });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execute-orchestrator-workflow.cjs.js","sources":["../../../../src/service/handlers/import/execute-orchestrator-workflow.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DiscoveryApi } from '@backstage/plugin-permission-common';\n\nimport {\n AuthToken,\n Configuration,\n DefaultApi,\n ExecuteWorkflowRequestDTO,\n} from '@red-hat-developer-hub/backstage-plugin-orchestrator-common';\n\nimport {\n OrchestratorWorkflowDao,\n RepositoryDao,\n} from '../../../database/repositoryDao';\nimport { Components, ImportRequest } from '../../../generated/openapi';\nimport { GithubApiService } from '../../../github';\nimport { GitlabApiService } from '../../../gitlab';\nimport { HandlerResponse } from '../handlers';\nimport { sortImports } from './bulkImports';\n\nexport type CreateWorkflowImportJobsArgs = {\n orchestratorWorkflowId: string;\n discovery: DiscoveryApi;\n
|
|
1
|
+
{"version":3,"file":"execute-orchestrator-workflow.cjs.js","sources":["../../../../src/service/handlers/import/execute-orchestrator-workflow.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type {\n AuthService,\n HttpAuthService,\n} from '@backstage/backend-plugin-api';\nimport { DiscoveryApi } from '@backstage/plugin-permission-common';\n\nimport type { Request } from 'express';\n\nimport {\n AuthToken,\n Configuration,\n DefaultApi,\n ExecuteWorkflowRequestDTO,\n} from '@red-hat-developer-hub/backstage-plugin-orchestrator-common';\n\nimport {\n OrchestratorWorkflowDao,\n RepositoryDao,\n} from '../../../database/repositoryDao';\nimport { Components, ImportRequest } from '../../../generated/openapi';\nimport { GithubApiService } from '../../../github';\nimport { GitlabApiService } from '../../../gitlab';\nimport { HandlerResponse } from '../handlers';\nimport { sortImports } from './bulkImports';\n\nexport type CreateWorkflowImportJobsArgs = {\n orchestratorWorkflowId: string;\n discovery: DiscoveryApi;\n auth: AuthService;\n httpAuth: HttpAuthService;\n req: Request;\n requestBody: ImportRequest[];\n orchestratorWorkflowDao: OrchestratorWorkflowDao;\n orchestratorRepositoryDao: RepositoryDao<'orchestrator_repositories'>;\n githubApiService: GithubApiService;\n gitlabApiService: GitlabApiService;\n};\n\nexport async function createWorkflowImportJobs(\n args: CreateWorkflowImportJobsArgs,\n): Promise<HandlerResponse<Components.Schemas.Import[]>> {\n const {\n orchestratorWorkflowId,\n discovery,\n auth,\n httpAuth,\n req,\n requestBody,\n orchestratorWorkflowDao,\n orchestratorRepositoryDao,\n githubApiService,\n gitlabApiService,\n } = args;\n\n if (requestBody.length === 0) {\n return {\n statusCode: 400,\n responseBody: [],\n };\n }\n\n const result: Components.Schemas.Import[] = [];\n const baseUrl = await discovery.getBaseUrl('orchestrator');\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: await httpAuth.credentials(req),\n targetPluginId: 'orchestrator',\n });\n const apiConfig = new Configuration();\n\n // Initialize the client\n const orchestratorApi = new DefaultApi(apiConfig, baseUrl);\n\n for (const repo of requestBody) {\n if (!repo.repository.url) {\n continue;\n }\n\n let workflowStatus: Components.Schemas.WorkflowImportStatus | undefined;\n try {\n const approvalTool = repo.approvalTool ?? 'GIT';\n\n const authTokens: AuthToken[] = [];\n if (approvalTool === 'GIT') {\n const creds = await githubApiService.getAppInstallationCredentials(\n repo.repository.url,\n );\n authTokens.push({ token: creds?.token, provider: 'github' });\n }\n if (approvalTool === 'GITLAB') {\n const creds = await gitlabApiService.getCredentials(\n repo.repository.url,\n );\n authTokens.push({ token: creds?.token, provider: 'gitlab' });\n }\n\n const requestDTO: ExecuteWorkflowRequestDTO = {\n inputData: {\n owner: repo.repository.organization,\n repo: repo.repository.name,\n baseBranch: repo.repository.defaultBranch,\n targetBranch: `bulk-import-orchestrator`,\n approvalTool: approvalTool,\n },\n authTokens,\n };\n\n // Execute a workflow\n const wfResult = await orchestratorApi.executeWorkflow(\n orchestratorWorkflowId,\n requestDTO,\n {\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n },\n );\n\n const repositoryId = await orchestratorRepositoryDao.insertRepository(\n repo.repository.url,\n wfResult.data.id,\n approvalTool,\n );\n await orchestratorWorkflowDao.insertWorkflow(\n wfResult.data.id,\n repositoryId,\n );\n\n const response = await orchestratorApi.getInstanceById(wfResult.data.id, {\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n });\n workflowStatus =\n `WORKFLOW_${(response.data.state as string)?.toLocaleUpperCase()}` as Components.Schemas.WorkflowImportStatus;\n\n result.push({\n repository: repo.repository,\n workflow: { workflowId: wfResult.data.id },\n status: workflowStatus,\n });\n } catch (error: any) {\n result.push({\n repository: repo.repository,\n status: workflowStatus ?? 'WORKFLOW_ABORTED',\n errors: [(error as Error).message],\n });\n }\n }\n\n sortImports(result);\n\n return {\n statusCode: 202,\n responseBody: result,\n };\n}\n"],"names":["Configuration","DefaultApi","sortImports"],"mappings":";;;;;AAqDA,eAAsB,yBACpB,IAAA,EACuD;AACvD,EAAA,MAAM;AAAA,IACJ,sBAAA;AAAA,IACA,SAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,GAAA;AAAA,IACA,WAAA;AAAA,IACA,uBAAA;AAAA,IACA,yBAAA;AAAA,IACA,gBAAA;AAAA,IACA;AAAA,GACF,GAAI,IAAA;AAEJ,EAAA,IAAI,WAAA,CAAY,WAAW,CAAA,EAAG;AAC5B,IAAA,OAAO;AAAA,MACL,UAAA,EAAY,GAAA;AAAA,MACZ,cAAc;AAAC,KACjB;AAAA,EACF;AAEA,EAAA,MAAM,SAAsC,EAAC;AAC7C,EAAA,MAAM,OAAA,GAAU,MAAM,SAAA,CAAU,UAAA,CAAW,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AAQ,CAAE,KAAA,CAAgB,OAAO;AAAA,OAClC,CAAA;AAAA,IACH;AAAA,EACF;AAEA,EAAAC,uBAAA,CAAY,MAAM,CAAA;AAElB,EAAA,OAAO;AAAA,IACL,UAAA,EAAY,GAAA;AAAA,IACZ,YAAA,EAAc;AAAA,GAChB;AACF;;;;"}
|
|
@@ -339,17 +339,18 @@ async function createRouter(options) {
|
|
|
339
339
|
pageSize,
|
|
340
340
|
search
|
|
341
341
|
);
|
|
342
|
-
const token = getBearerTokenFromReq(req);
|
|
343
342
|
for (const repo of repositories.data) {
|
|
344
343
|
const response = await bulkImports.findOrchestratorImportStatusByRepo(
|
|
345
344
|
{
|
|
346
345
|
logger,
|
|
347
346
|
orchestratorRepositoryDao,
|
|
348
347
|
orchestratorWorkflowDao,
|
|
349
|
-
discovery
|
|
348
|
+
discovery,
|
|
349
|
+
auth: auth$1,
|
|
350
|
+
httpAuth,
|
|
351
|
+
req
|
|
350
352
|
},
|
|
351
353
|
repo.url,
|
|
352
|
-
token,
|
|
353
354
|
true
|
|
354
355
|
);
|
|
355
356
|
if (response.responseBody) {
|
|
@@ -422,18 +423,19 @@ async function createRouter(options) {
|
|
|
422
423
|
`Missing required config value: 'bulkImport.orchestratorWorkflow'`
|
|
423
424
|
);
|
|
424
425
|
}
|
|
425
|
-
const token = getBearerTokenFromReq(req);
|
|
426
426
|
const response = await executeOrchestratorWorkflow.createWorkflowImportJobs({
|
|
427
427
|
orchestratorWorkflowId,
|
|
428
428
|
discovery,
|
|
429
|
-
|
|
429
|
+
auth: auth$1,
|
|
430
|
+
httpAuth,
|
|
431
|
+
req,
|
|
430
432
|
requestBody: c.request.requestBody,
|
|
431
433
|
orchestratorWorkflowDao,
|
|
432
434
|
orchestratorRepositoryDao,
|
|
433
435
|
githubApiService: githubApiService$1,
|
|
434
436
|
gitlabApiService: gitlabApiService$1
|
|
435
437
|
});
|
|
436
|
-
res.status(response.statusCode).json(response.responseBody);
|
|
438
|
+
return res.status(response.statusCode).json(response.responseBody);
|
|
437
439
|
}
|
|
438
440
|
);
|
|
439
441
|
api.register(
|
|
@@ -496,16 +498,17 @@ async function createRouter(options) {
|
|
|
496
498
|
if (!q.repo?.trim()) {
|
|
497
499
|
throw new Error("missing or blank parameter");
|
|
498
500
|
}
|
|
499
|
-
const token = getBearerTokenFromReq(req);
|
|
500
501
|
const response = await bulkImports.findOrchestratorImportStatusByRepo(
|
|
501
502
|
{
|
|
502
503
|
logger,
|
|
503
504
|
orchestratorRepositoryDao,
|
|
504
505
|
orchestratorWorkflowDao,
|
|
505
|
-
discovery
|
|
506
|
+
discovery,
|
|
507
|
+
auth: auth$1,
|
|
508
|
+
httpAuth,
|
|
509
|
+
req
|
|
506
510
|
},
|
|
507
|
-
q.repo
|
|
508
|
-
token
|
|
511
|
+
q.repo
|
|
509
512
|
);
|
|
510
513
|
return res.status(response.statusCode).json(response.responseBody);
|
|
511
514
|
}
|
|
@@ -727,13 +730,6 @@ function getFindImportsParams(c) {
|
|
|
727
730
|
sortOrder: q.sortOrder
|
|
728
731
|
};
|
|
729
732
|
}
|
|
730
|
-
function getBearerTokenFromReq(req) {
|
|
731
|
-
const header = req.header("authorization") ?? req.headers.authorization;
|
|
732
|
-
if (header?.startsWith(`Bearer `)) {
|
|
733
|
-
return header.replace("Bearer ", "");
|
|
734
|
-
}
|
|
735
|
-
throw new errors.InputError(`Request provided without token`);
|
|
736
|
-
}
|
|
737
733
|
|
|
738
734
|
exports.createRouter = createRouter;
|
|
739
735
|
//# sourceMappingURL=router.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MiddlewareFactory } from '@backstage/backend-defaults/rootHttpRouter';\nimport type {\n AuditorService,\n AuditorServiceEvent,\n AuthService,\n CacheService,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport { InputError } from '@backstage/errors';\nimport type { CatalogService } from '@backstage/plugin-catalog-node';\nimport type { PermissionEvaluator } from '@backstage/plugin-permission-common';\n\nimport { fullFormats } from 'ajv-formats/dist/formats';\nimport express, { Router, type Request, type Response } from 'express';\nimport {\n Document,\n OpenAPIBackend,\n type Context,\n type Request as OpenAPIRequest,\n} from 'openapi-backend';\n\nimport { CatalogHttpClient } from '../catalog/catalogHttpClient';\nimport { CatalogInfoGenerator } from '../catalog/catalogInfoGenerator';\nimport { migrate } from '../database/migration';\nimport {\n OrchestratorWorkflowDao,\n RepositoryDao,\n ScaffolderTaskDao,\n TaskLocationsDao,\n} from '../database/repositoryDao';\nimport type { Components, Paths, SourceImport } from '../generated/openapi.d';\nimport { openApiDocument } from '../generated/openapidocument';\nimport { GithubApiService } from '../github';\nimport { GitlabApiService } from '../gitlab';\nimport {\n getImportTemplateRef,\n parseGitURLForApprovalTool,\n permissionCheck,\n} from '../helpers';\nimport { auditCreateEvent } from '../helpers/auditorUtils';\nimport {\n createImportJobs,\n deleteImportByRepo,\n deleteRepositoryRecord,\n findAllImports,\n findImportStatusByRepo,\n findOrchestratorImportStatusByRepo,\n findTaskImportStatusByRepo,\n sortImports,\n} from './handlers/import';\nimport { createWorkflowImportJobs } from './handlers/import/execute-orchestrator-workflow';\nimport { createTaskImportJobs } from './handlers/import/execute-template';\nimport { findAllOrganizations } from './handlers/organization';\nimport { ping } from './handlers/ping';\nimport {\n findAllRepositories,\n findRepositoriesByOrganization,\n} from './handlers/repository';\nimport { findAllSCMHosts } from './handlers/scm/scm';\n\n/**\n * Router Options\n * @public\n */\nexport interface RouterOptions {\n logger: LoggerService;\n permissions: PermissionEvaluator;\n config: Config;\n cache: CacheService;\n discovery: DiscoveryService;\n httpAuth: HttpAuthService;\n auth: AuthService;\n catalog: CatalogService;\n auditor: AuditorService;\n database: DatabaseService;\n}\n\nnamespace Operations {\n export const PING = 'ping';\n export const FIND_ALL_SCM_HOSTS = 'findAllSCMHosts';\n export const FIND_ALL_ORGANIZATIONS = 'findAllOrganizations';\n export const FIND_ALL_REPOSITORIES = 'findAllRepositories';\n\n export const FIND_REPOSITORIES_BY_ORGANIZATION =\n 'findRepositoriesByOrganization';\n\n export const FIND_ALL_IMPORTS = 'findAllImports';\n export const FIND_ALL_TASK_IMPORTS = 'findAllTaskImports';\n export const FIND_ALL_ORCHESTRATOR_WORKFLOW_IMPORTS =\n 'findAllOrchestratorWorkflowImports';\n\n export const CREATE_IMPORT_JOBS = 'createImportJobs';\n export const CREATE_TASK_IMPORT_JOBS = 'createTaskImportJobs';\n export const CREATE_ORCHESTRATOR_WORKFLOW_JOBS =\n 'createOrchestratorWorkflowJobs';\n\n export const FIND_IMPORT_STATUS_BY_REPO = 'findImportStatusByRepo';\n export const FIND_TASK_IMPORT_STATUS_BY_REPO = 'findTaskImportStatusByRepo';\n export const FIND_ORCHESTRATOR_IMPORT_STATUS_BY_REPO =\n 'findOrchestratorImportStatusByRepo';\n\n export const DELETE_IMPORT_BY_REPO = 'deleteImportByRepo';\n export const DELETE_TASK_IMPORT_BY_REPO = 'deleteTaskImportByRepo';\n export const DELETE_ORCHESTRATOR_IMPORT_BY_REPO =\n 'deleteOrchestratorImportByRepo';\n}\n\nconst SCM_TOKENS_MAX_BYTES = 4096;\n\nconst isValidTokenMap = (v: unknown): v is Record<string, string> =>\n typeof v === 'object' &&\n v !== null &&\n Object.values(v).every(val => typeof val === 'string' && val.length > 0);\n\nfunction parseScmTokensHeader(\n rawTokenHeader: string | undefined,\n logger: LoggerService,\n): Record<string, string> | undefined {\n let token: Record<string, string> | undefined;\n if (!rawTokenHeader) return undefined;\n if (rawTokenHeader.length > SCM_TOKENS_MAX_BYTES) {\n logger.warn('x-scm-tokens header exceeds maximum allowed size; ignoring');\n return undefined;\n }\n try {\n token = JSON.parse(rawTokenHeader) as Record<string, string>;\n if (typeof token !== 'object' || token === null || Array.isArray(token)) {\n throw new Error('x-scm-tokens must be a JSON object');\n }\n } catch (e) {\n throw new InputError(\n `Invalid x-scm-tokens header: ${(e as Error).message}`,\n );\n }\n\n if (!isValidTokenMap(token)) {\n throw new InputError(\n 'Invalid x-scm-tokens header: all values must be non-empty strings',\n );\n }\n return token;\n}\n\n/**\n * Router\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n httpAuth,\n auth,\n permissions,\n config,\n cache,\n discovery,\n catalog,\n auditor,\n database,\n } = options;\n\n const knex = await migrate(database);\n const repositoryDao = new RepositoryDao(knex, logger, 'repositories');\n const taskDao = new ScaffolderTaskDao(knex);\n const taskLocationsDao = new TaskLocationsDao(knex);\n const orchestratorRepositoryDao = new RepositoryDao(\n knex,\n logger,\n 'orchestrator_repositories',\n );\n const orchestratorWorkflowDao = new OrchestratorWorkflowDao(knex);\n // GitHub and GitLab both implement the GitApiService interface; the router\n // selects the appropriate service per request based on approvalTool.\n const githubApiService = new GithubApiService(logger, config, cache);\n const gitlabApiService = new GitlabApiService(logger, config, cache);\n const catalogHttpClient = new CatalogHttpClient({\n logger,\n config,\n auth,\n catalog,\n });\n const catalogInfoGenerator = new CatalogInfoGenerator(\n logger,\n catalogHttpClient,\n );\n\n // create openapi requests handler\n const api = new OpenAPIBackend({\n ajvOpts: {\n verbose: true,\n formats: fullFormats, // open issue: https://github.com/openapistack/openapi-backend/issues/280\n },\n validate: true,\n definition: openApiDocument,\n handlers: {\n validationFail: async (c, _req: Request, res: Response) =>\n res.status(400).json({ err: c.validation.errors }),\n notFound: async (_c, req: Request, res: Response) =>\n res.status(404).json({ err: `'${req.method} ${req.path}' not found` }),\n notImplemented: async (_c, req: Request, res: Response) =>\n res\n .status(500)\n .json({ err: `'${req.method} ${req.path}' not implemented` }),\n },\n });\n\n const templateRef = config.getOptionalString('bulkImport.importTemplate');\n let finalTemplateRef: string | undefined;\n if (templateRef) {\n finalTemplateRef = getImportTemplateRef(templateRef);\n }\n\n const orchestratorWorkflowId = config.getOptionalString(\n 'bulkImport.orchestratorWorkflow',\n );\n\n await api.init();\n\n api.register(\n Operations.PING,\n async (_c: Context, _req: Request, res: Response) => {\n const result = await ping(logger);\n return res.status(result.statusCode).json(result.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ALL_SCM_HOSTS,\n async (_c: Context, _req: Request, res: Response) => {\n const result = await findAllSCMHosts(config);\n return res.status(result.statusCode).json(result.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ALL_ORGANIZATIONS,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindAllOrganizations.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n q.pagePerIntegration = stringToNumber(q.pagePerIntegration);\n q.sizePerIntegration = stringToNumber(q.sizePerIntegration);\n const response = await findAllOrganizations(\n logger,\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n q.search,\n q.pagePerIntegration,\n q.sizePerIntegration,\n );\n return res.status(response.statusCode).json({\n errors: response.responseBody?.errors,\n organizations: response.responseBody?.organizations,\n totalCount: response.responseBody?.totalCount,\n pagePerIntegration: response.responseBody?.pagePerIntegration,\n sizePerIntegration: response.responseBody?.sizePerIntegration,\n approvalTool: q.approvalTool,\n } as Components.Schemas.OrganizationList);\n },\n );\n\n api.register(\n Operations.FIND_ALL_REPOSITORIES,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindAllRepositories.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n q.pagePerIntegration = stringToNumber(q.pagePerIntegration);\n q.sizePerIntegration = stringToNumber(q.sizePerIntegration);\n q.checkImportStatus = stringToBoolean(q.checkImportStatus);\n\n const userTokens = res.locals.scmTokens as\n Record<string, string> | undefined;\n\n if (!userTokens || Object.keys(userTokens).length === 0) {\n return res.status(401).json({\n error:\n 'User SCM credentials are required to list repositories. Ensure the SCM OAuth integration is configured.',\n });\n }\n\n const response = await findAllRepositories(\n {\n logger,\n config,\n gitApiService:\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n catalogHttpClient,\n },\n {\n search: q.search,\n checkStatus: q.checkImportStatus,\n pageNumber: q.pagePerIntegration,\n pageSize: q.sizePerIntegration,\n userTokens,\n },\n );\n const repos = response.responseBody?.repositories;\n return res.status(response.statusCode).json({\n errors: response.responseBody?.errors,\n repositories: repos,\n totalCount: response.responseBody?.totalCount,\n pagePerIntegration: q.pagePerIntegration,\n sizePerIntegration: q.sizePerIntegration,\n approvalTool: q.approvalTool,\n } as Components.Schemas.RepositoryList);\n },\n );\n\n api.register(\n Operations.FIND_REPOSITORIES_BY_ORGANIZATION,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindRepositoriesByOrganization.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n q.pagePerIntegration = stringToNumber(q.pagePerIntegration);\n q.sizePerIntegration = stringToNumber(q.sizePerIntegration);\n q.checkImportStatus = stringToBoolean(q.checkImportStatus);\n\n const userTokens = res.locals.scmTokens as\n Record<string, string> | undefined;\n\n if (!userTokens || Object.keys(userTokens).length === 0) {\n return res.status(401).json({\n error:\n 'User SCM credentials are required to list repositories. Ensure the SCM OAuth integration is configured.',\n });\n }\n\n const response = await findRepositoriesByOrganization(\n {\n logger,\n config,\n gitApiService:\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n catalogHttpClient,\n },\n c.request.params.organizationName?.toString(),\n q.search,\n q.checkImportStatus,\n q.pagePerIntegration,\n q.sizePerIntegration,\n userTokens,\n );\n const repos = response.responseBody?.repositories;\n return res.status(response.statusCode).json({\n errors: response.responseBody?.errors,\n repositories: repos,\n totalCount: response.responseBody?.totalCount,\n pagePerIntegration: q.pagePerIntegration,\n sizePerIntegration: q.sizePerIntegration,\n approvalTool: q.approvalTool,\n } as Components.Schemas.RepositoryList);\n },\n );\n\n api.register(\n Operations.FIND_ALL_IMPORTS,\n async (c: Context, _req: Request, res: Response) => {\n const {\n pageNumber,\n pageSize,\n apiVersion,\n search,\n sortColumn,\n sortOrder,\n } = getFindImportsParams(c);\n const response = await findAllImports(\n {\n logger,\n config,\n githubApiService,\n gitlabApiService,\n catalogHttpClient,\n },\n {\n apiVersion,\n },\n {\n search,\n pageNumber,\n pageSize,\n sortColumn,\n sortOrder,\n },\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n api.register(\n Operations.FIND_ALL_TASK_IMPORTS,\n async (c: Context, _req: Request, res: Response) => {\n const { pageNumber, pageSize, search, sortColumn, sortOrder } =\n getFindImportsParams(c);\n const imports: SourceImport[] = [];\n const repositories = await repositoryDao.findRepositories(\n pageNumber,\n pageSize,\n search,\n );\n\n for (const repo of repositories.data) {\n const response = await findTaskImportStatusByRepo(\n {\n logger,\n config,\n githubApiService,\n gitlabApiService,\n catalogHttpClient,\n repositoryDao,\n taskDao,\n taskLocationsDao,\n discovery,\n auth,\n },\n repo.url,\n true,\n );\n if (response.responseBody) {\n imports.push(response.responseBody);\n }\n }\n\n sortImports(imports, sortColumn, sortOrder);\n\n const responseBody: Components.Schemas.ImportJobListV2 = {\n imports,\n totalCount: repositories.total,\n page: pageNumber || 1,\n size: pageSize || 5,\n };\n\n return res.status(200).json(responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ALL_ORCHESTRATOR_WORKFLOW_IMPORTS,\n async (c: Context, req: Request, res: Response) => {\n const { pageNumber, pageSize, search, sortColumn, sortOrder } =\n getFindImportsParams(c);\n const imports: SourceImport[] = [];\n const repositories = await orchestratorRepositoryDao.findRepositories(\n pageNumber,\n pageSize,\n search,\n );\n\n const token = getBearerTokenFromReq(req);\n\n for (const repo of repositories.data) {\n const response = await findOrchestratorImportStatusByRepo(\n {\n logger,\n orchestratorRepositoryDao,\n orchestratorWorkflowDao,\n discovery,\n },\n repo.url,\n token,\n true,\n );\n if (response.responseBody) {\n imports.push(response.responseBody);\n }\n }\n\n sortImports(imports, sortColumn, sortOrder);\n\n const responseBody: Components.Schemas.ImportJobListV2 = {\n imports,\n totalCount: repositories.total,\n page: pageNumber || 1,\n size: pageSize || 5,\n };\n\n return res.status(200).json(responseBody);\n },\n );\n\n api.register(\n Operations.CREATE_IMPORT_JOBS,\n async (\n c: Context<Paths.CreateImportJobs.RequestBody>,\n _req: Request,\n res: Response,\n ) => {\n const q: Paths.CreateImportJobs.QueryParameters = {\n ...c.request.query,\n };\n q.dryRun = stringToBoolean(q.dryRun);\n const response = await createImportJobs(\n {\n logger,\n config,\n auth,\n gitlabApiService,\n githubApiService,\n catalogInfoGenerator,\n catalogHttpClient,\n },\n {\n importRequests: c.request.requestBody,\n dryRun: q.dryRun,\n },\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.CREATE_TASK_IMPORT_JOBS,\n async (\n c: Context<Paths.CreateImportJobs.RequestBody>,\n _req: Request,\n res: Response,\n ) => {\n if (!finalTemplateRef) {\n throw new Error(\n `Missing required config value: 'bulkImport.importTemplate'`,\n );\n }\n const response = await createTaskImportJobs(\n finalTemplateRef,\n discovery,\n logger,\n auth,\n config,\n repositoryDao,\n taskDao,\n taskLocationsDao,\n c.request.requestBody,\n githubApiService,\n );\n\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.CREATE_ORCHESTRATOR_WORKFLOW_JOBS,\n async (\n c: Context<Paths.CreateImportJobs.RequestBody>,\n req: Request,\n res: Response,\n ) => {\n if (!orchestratorWorkflowId) {\n throw new Error(\n `Missing required config value: 'bulkImport.orchestratorWorkflow'`,\n );\n }\n\n const token = getBearerTokenFromReq(req);\n\n const response = await createWorkflowImportJobs({\n orchestratorWorkflowId,\n discovery,\n token,\n requestBody: c.request.requestBody,\n orchestratorWorkflowDao,\n orchestratorRepositoryDao,\n githubApiService,\n gitlabApiService,\n });\n\n res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_TASK_IMPORT_STATUS_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindImportStatusByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank parameter');\n }\n const response = await findTaskImportStatusByRepo(\n {\n logger,\n config,\n githubApiService,\n gitlabApiService,\n catalogHttpClient,\n repositoryDao,\n taskDao,\n taskLocationsDao,\n discovery,\n auth,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_IMPORT_STATUS_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindImportStatusByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank parameter');\n }\n const response = await findImportStatusByRepo(\n {\n logger,\n config,\n gitApiService:\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n catalogHttpClient,\n approvalTool: q.approvalTool,\n },\n q.repo,\n q.defaultBranch,\n true,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ORCHESTRATOR_IMPORT_STATUS_BY_REPO,\n async (c: Context, req: Request, res: Response) => {\n const q: Paths.FindImportStatusByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank parameter');\n }\n const token = getBearerTokenFromReq(req);\n const response = await findOrchestratorImportStatusByRepo(\n {\n logger,\n orchestratorRepositoryDao,\n orchestratorWorkflowDao,\n discovery,\n },\n q.repo,\n token,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.DELETE_TASK_IMPORT_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.DeleteImportByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank \"repo\" parameter');\n }\n const response = await deleteRepositoryRecord(\n {\n logger,\n dao: repositoryDao,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.DELETE_IMPORT_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.DeleteImportByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank \"repo\" parameter');\n }\n const response = await deleteImportByRepo(\n {\n logger,\n config,\n gitApiService:\n parseGitURLForApprovalTool(q.repo) === 'GITLAB'\n ? gitlabApiService\n : githubApiService,\n catalogHttpClient,\n },\n q.repo,\n q.defaultBranch,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.DELETE_ORCHESTRATOR_IMPORT_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.DeleteImportByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank \"repo\" parameter');\n }\n const response = await deleteRepositoryRecord(\n {\n logger,\n dao: orchestratorRepositoryDao,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n const router = Router();\n router.use(express.json());\n\n // Strip x-scm-tokens from req.headers before the permission check and audit\n // middleware run so that OAuth tokens are never captured in audit logs.\n // The parsed map is stored in res.locals.scmTokens for handler use.\n router.use((req, res, next) => {\n const raw = req.headers['x-scm-tokens'];\n const rawStr = Array.isArray(raw) ? raw[0] : raw;\n delete req.headers['x-scm-tokens'];\n if (rawStr) {\n try {\n res.locals.scmTokens = parseScmTokensHeader(rawStr, logger);\n } catch (e) {\n next(e);\n return;\n }\n }\n next();\n });\n\n router.use(async (req, _res, next) => {\n if (req.path !== '/ping') {\n try {\n await permissionCheck(\n auditor,\n api.matchOperation(req as OpenAPIRequest)?.operationId,\n permissions,\n httpAuth,\n req,\n );\n } catch (e) {\n next(e);\n return;\n }\n }\n next();\n });\n\n router.use(async (req, res, next) => {\n const reqCast = req as OpenAPIRequest;\n const operationId = api.matchOperation(reqCast)?.operationId;\n\n const auditorEvent = await createAuditorEventByOperationId(\n operationId,\n req,\n auditor,\n );\n try {\n const response = (await api.handleRequest(reqCast, req, res)) as Response;\n auditorEvent?.success({ meta: { responseStatus: response.statusCode } });\n next();\n } catch (err: any) {\n auditorEvent?.fail({ error: err, meta: { responseStatus: 500 } });\n next(err);\n }\n });\n\n const middleware = MiddlewareFactory.create({ logger, config });\n router.use(middleware.error());\n\n return router;\n}\n\nasync function createAuditorEventByOperationId(\n operationId: string | undefined,\n req: Request,\n auditor: AuditorService,\n): Promise<AuditorServiceEvent | undefined> {\n let auditorEvent;\n switch (operationId) {\n case Operations.PING:\n auditorEvent = await auditCreateEvent(auditor, 'ping', req);\n break;\n case Operations.FIND_ALL_SCM_HOSTS:\n auditorEvent = await auditCreateEvent(auditor, 'scm-hosts-read', req);\n break;\n\n case Operations.FIND_ALL_ORGANIZATIONS:\n auditorEvent = await auditCreateEvent(auditor, 'org-read', req, {\n queryType: req.query.search ? 'by-query' : 'all',\n search: req.query?.search,\n });\n break;\n case Operations.FIND_ALL_REPOSITORIES:\n auditorEvent = await auditCreateEvent(auditor, 'repo-read', req, {\n queryType: req.query.search ? 'by-query' : 'all',\n search: req.query.search,\n });\n break;\n case Operations.FIND_REPOSITORIES_BY_ORGANIZATION: {\n const organizationName = req.params.organizationName?.toString();\n auditorEvent = await auditCreateEvent(auditor, 'repo-read', req, {\n queryType: 'by-org',\n organizationName,\n });\n break;\n }\n case Operations.FIND_ALL_IMPORTS:\n case Operations.FIND_ALL_TASK_IMPORTS:\n case Operations.FIND_ALL_ORCHESTRATOR_WORKFLOW_IMPORTS:\n auditorEvent = await auditCreateEvent(auditor, 'import-read', req, {\n queryType: req.query.search ? 'by-query' : 'all',\n search: req.query.search,\n });\n break;\n case Operations.CREATE_IMPORT_JOBS:\n case Operations.CREATE_TASK_IMPORT_JOBS:\n case Operations.CREATE_ORCHESTRATOR_WORKFLOW_JOBS:\n auditorEvent = await auditCreateEvent(auditor, 'import-write', req, {\n actionType: 'create',\n });\n break;\n case Operations.FIND_IMPORT_STATUS_BY_REPO:\n case Operations.FIND_TASK_IMPORT_STATUS_BY_REPO:\n case Operations.FIND_ORCHESTRATOR_IMPORT_STATUS_BY_REPO:\n auditorEvent = await auditCreateEvent(\n auditor,\n 'import-status-read',\n req,\n { queryType: 'by-query', repo: req.query.repo },\n );\n break;\n case Operations.DELETE_IMPORT_BY_REPO:\n case Operations.DELETE_TASK_IMPORT_BY_REPO:\n case Operations.DELETE_ORCHESTRATOR_IMPORT_BY_REPO:\n auditorEvent = await auditCreateEvent(auditor, 'import-write', req, {\n actionType: 'delete',\n repository: req.query.repo,\n });\n break;\n case undefined:\n auditorEvent = await auditCreateEvent(auditor, operationId, req);\n break;\n default:\n // do nothing\n break;\n }\n return auditorEvent;\n}\n\nfunction stringToNumber(s: number | undefined): number | undefined {\n return s ? Number.parseInt(s.toString(), 10) : undefined;\n}\n\nfunction stringToBoolean(s: boolean | undefined): boolean | undefined {\n if (!s) {\n return undefined;\n }\n return s.toString() === 'true';\n}\nfunction getFindImportsParams(c: Context<any, any, any, any, any, Document>): {\n pageNumber?: number;\n pageSize?: number;\n apiVersion?: Paths.FindAllImports.Parameters.ApiVersion;\n search?: string;\n sortColumn?: Components.Parameters.SortColumnQueryParam;\n sortOrder?: Components.Parameters.SortOrderQueryParam;\n} {\n const h: Paths.FindAllImports.HeaderParameters = {\n ...c.request.headers,\n };\n const apiVersion = h['api-version'];\n const q: Paths.FindAllImports.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n let pageNumber: number | undefined;\n let pageSize: number | undefined;\n if (apiVersion === undefined || apiVersion === 'v1') {\n // pagePerIntegration and sizePerIntegration deprecated in v1. 'page' and 'size' take precedence.\n pageNumber = stringToNumber(q.page || q.pagePerIntegration);\n pageSize = stringToNumber(q.size || q.sizePerIntegration);\n } else {\n // pagePerIntegration and sizePerIntegration removed in v2+ and replaced by 'page' and 'size'.\n pageNumber = stringToNumber(q.page);\n pageSize = stringToNumber(q.size);\n }\n return {\n pageNumber,\n pageSize,\n apiVersion: apiVersion,\n search: q.search,\n sortColumn: q.sortColumn,\n sortOrder: q.sortOrder,\n };\n}\n\nfunction getBearerTokenFromReq(req: express.Request): string {\n const header = req.header('authorization') ?? req.headers.authorization;\n if (header?.startsWith(`Bearer `)) {\n return header.replace('Bearer ', '');\n }\n throw new InputError(`Request provided without token`);\n}\n"],"names":["Operations","InputError","auth","migrate","repositoryDao","RepositoryDao","ScaffolderTaskDao","TaskLocationsDao","OrchestratorWorkflowDao","githubApiService","GithubApiService","gitlabApiService","GitlabApiService","catalogHttpClient","CatalogHttpClient","catalogInfoGenerator","CatalogInfoGenerator","OpenAPIBackend","fullFormats","openApiDocument","getImportTemplateRef","ping","findAllSCMHosts","findAllOrganizations","findAllRepositories","findRepositoriesByOrganization","findAllImports","findTaskImportStatusByRepo","sortImports","findOrchestratorImportStatusByRepo","createImportJobs","createTaskImportJobs","createWorkflowImportJobs","findImportStatusByRepo","deleteRepositoryRecord","deleteImportByRepo","parseGitURLForApprovalTool","Router","express","permissionCheck","MiddlewareFactory","auditCreateEvent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,IAAU,UAAA;AAAA,CAAV,CAAUA,WAAAA,KAAV;AACS,EAAMA,YAAA,IAAA,GAAO,MAAA;AACb,EAAMA,YAAA,kBAAA,GAAqB,iBAAA;AAC3B,EAAMA,YAAA,sBAAA,GAAyB,sBAAA;AAC/B,EAAMA,YAAA,qBAAA,GAAwB,qBAAA;AAE9B,EAAMA,YAAA,iCAAA,GACX,gCAAA;AAE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AA,IAAa,UAAA,KAAe,IAAA,EAAM;AAEnD,IAAA,UAAA,GAAa,cAAA,CAAe,CAAA,CAAE,IAAA,IAAQ,CAAA,CAAE,kBAAkB,CAAA;AAC1D,IAAA,QAAA,GAAW,cAAA,CAAe,CAAA,CAAE,IAAA,IAAQ,CAAA,CAAE,kBAAkB,CAAA;AAAA,EAC1D,CAAA,MAAO;AAEL,IAAA,UAAA,GAAa,cAAA,CAAe,EAAE,IAAI,CAAA;AAClC,IAAA,QAAA,GAAW,cAAA,CAAe,EAAE,IAAI,CAAA;AAAA,EAClC;AACA,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAQ,CAAA,CAAE,MAAA;AAAA,IACV,YAAY,CAAA,CAAE,UAAA;AAAA,IACd,WAAW,CAAA,CAAE;AAAA,GACf;AACF;AAEA,SAAS,sBAAsB,GAAA,EAA8B;AAC3D,EAAA,MAAM,SAAS,GAAA,CAAI,MAAA,CAAO,eAAe,CAAA,IAAK,IAAI,OAAA,CAAQ,aAAA;AAC1D,EAAA,IAAI,MAAA,EAAQ,UAAA,CAAW,CAAA,OAAA,CAAS,CAAA,EAAG;AACjC,IAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,SAAA,EAAW,EAAE,CAAA;AAAA,EACrC;AACA,EAAA,MAAM,IAAIxC,kBAAW,CAAA,8BAAA,CAAgC,CAAA;AACvD;;;;"}
|
|
1
|
+
{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MiddlewareFactory } from '@backstage/backend-defaults/rootHttpRouter';\nimport type {\n AuditorService,\n AuditorServiceEvent,\n AuthService,\n CacheService,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport { InputError } from '@backstage/errors';\nimport type { CatalogService } from '@backstage/plugin-catalog-node';\nimport type { PermissionEvaluator } from '@backstage/plugin-permission-common';\n\nimport { fullFormats } from 'ajv-formats/dist/formats';\nimport express, { Router, type Request, type Response } from 'express';\nimport {\n Document,\n OpenAPIBackend,\n type Context,\n type Request as OpenAPIRequest,\n} from 'openapi-backend';\n\nimport { CatalogHttpClient } from '../catalog/catalogHttpClient';\nimport { CatalogInfoGenerator } from '../catalog/catalogInfoGenerator';\nimport { migrate } from '../database/migration';\nimport {\n OrchestratorWorkflowDao,\n RepositoryDao,\n ScaffolderTaskDao,\n TaskLocationsDao,\n} from '../database/repositoryDao';\nimport type { Components, Paths, SourceImport } from '../generated/openapi.d';\nimport { openApiDocument } from '../generated/openapidocument';\nimport { GithubApiService } from '../github';\nimport { GitlabApiService } from '../gitlab';\nimport {\n getImportTemplateRef,\n parseGitURLForApprovalTool,\n permissionCheck,\n} from '../helpers';\nimport { auditCreateEvent } from '../helpers/auditorUtils';\nimport {\n createImportJobs,\n deleteImportByRepo,\n deleteRepositoryRecord,\n findAllImports,\n findImportStatusByRepo,\n findOrchestratorImportStatusByRepo,\n findTaskImportStatusByRepo,\n sortImports,\n} from './handlers/import';\nimport { createWorkflowImportJobs } from './handlers/import/execute-orchestrator-workflow';\nimport { createTaskImportJobs } from './handlers/import/execute-template';\nimport { findAllOrganizations } from './handlers/organization';\nimport { ping } from './handlers/ping';\nimport {\n findAllRepositories,\n findRepositoriesByOrganization,\n} from './handlers/repository';\nimport { findAllSCMHosts } from './handlers/scm/scm';\n\n/**\n * Router Options\n * @public\n */\nexport interface RouterOptions {\n logger: LoggerService;\n permissions: PermissionEvaluator;\n config: Config;\n cache: CacheService;\n discovery: DiscoveryService;\n httpAuth: HttpAuthService;\n auth: AuthService;\n catalog: CatalogService;\n auditor: AuditorService;\n database: DatabaseService;\n}\n\nnamespace Operations {\n export const PING = 'ping';\n export const FIND_ALL_SCM_HOSTS = 'findAllSCMHosts';\n export const FIND_ALL_ORGANIZATIONS = 'findAllOrganizations';\n export const FIND_ALL_REPOSITORIES = 'findAllRepositories';\n\n export const FIND_REPOSITORIES_BY_ORGANIZATION =\n 'findRepositoriesByOrganization';\n\n export const FIND_ALL_IMPORTS = 'findAllImports';\n export const FIND_ALL_TASK_IMPORTS = 'findAllTaskImports';\n export const FIND_ALL_ORCHESTRATOR_WORKFLOW_IMPORTS =\n 'findAllOrchestratorWorkflowImports';\n\n export const CREATE_IMPORT_JOBS = 'createImportJobs';\n export const CREATE_TASK_IMPORT_JOBS = 'createTaskImportJobs';\n export const CREATE_ORCHESTRATOR_WORKFLOW_JOBS =\n 'createOrchestratorWorkflowJobs';\n\n export const FIND_IMPORT_STATUS_BY_REPO = 'findImportStatusByRepo';\n export const FIND_TASK_IMPORT_STATUS_BY_REPO = 'findTaskImportStatusByRepo';\n export const FIND_ORCHESTRATOR_IMPORT_STATUS_BY_REPO =\n 'findOrchestratorImportStatusByRepo';\n\n export const DELETE_IMPORT_BY_REPO = 'deleteImportByRepo';\n export const DELETE_TASK_IMPORT_BY_REPO = 'deleteTaskImportByRepo';\n export const DELETE_ORCHESTRATOR_IMPORT_BY_REPO =\n 'deleteOrchestratorImportByRepo';\n}\n\nconst SCM_TOKENS_MAX_BYTES = 4096;\n\nconst isValidTokenMap = (v: unknown): v is Record<string, string> =>\n typeof v === 'object' &&\n v !== null &&\n Object.values(v).every(val => typeof val === 'string' && val.length > 0);\n\nfunction parseScmTokensHeader(\n rawTokenHeader: string | undefined,\n logger: LoggerService,\n): Record<string, string> | undefined {\n let token: Record<string, string> | undefined;\n if (!rawTokenHeader) return undefined;\n if (rawTokenHeader.length > SCM_TOKENS_MAX_BYTES) {\n logger.warn('x-scm-tokens header exceeds maximum allowed size; ignoring');\n return undefined;\n }\n try {\n token = JSON.parse(rawTokenHeader) as Record<string, string>;\n if (typeof token !== 'object' || token === null || Array.isArray(token)) {\n throw new Error('x-scm-tokens must be a JSON object');\n }\n } catch (e) {\n throw new InputError(\n `Invalid x-scm-tokens header: ${(e as Error).message}`,\n );\n }\n\n if (!isValidTokenMap(token)) {\n throw new InputError(\n 'Invalid x-scm-tokens header: all values must be non-empty strings',\n );\n }\n return token;\n}\n\n/**\n * Router\n * @public\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n logger,\n httpAuth,\n auth,\n permissions,\n config,\n cache,\n discovery,\n catalog,\n auditor,\n database,\n } = options;\n\n const knex = await migrate(database);\n const repositoryDao = new RepositoryDao(knex, logger, 'repositories');\n const taskDao = new ScaffolderTaskDao(knex);\n const taskLocationsDao = new TaskLocationsDao(knex);\n const orchestratorRepositoryDao = new RepositoryDao(\n knex,\n logger,\n 'orchestrator_repositories',\n );\n const orchestratorWorkflowDao = new OrchestratorWorkflowDao(knex);\n // GitHub and GitLab both implement the GitApiService interface; the router\n // selects the appropriate service per request based on approvalTool.\n const githubApiService = new GithubApiService(logger, config, cache);\n const gitlabApiService = new GitlabApiService(logger, config, cache);\n const catalogHttpClient = new CatalogHttpClient({\n logger,\n config,\n auth,\n catalog,\n });\n const catalogInfoGenerator = new CatalogInfoGenerator(\n logger,\n catalogHttpClient,\n );\n\n // create openapi requests handler\n const api = new OpenAPIBackend({\n ajvOpts: {\n verbose: true,\n formats: fullFormats, // open issue: https://github.com/openapistack/openapi-backend/issues/280\n },\n validate: true,\n definition: openApiDocument,\n handlers: {\n validationFail: async (c, _req: Request, res: Response) =>\n res.status(400).json({ err: c.validation.errors }),\n notFound: async (_c, req: Request, res: Response) =>\n res.status(404).json({ err: `'${req.method} ${req.path}' not found` }),\n notImplemented: async (_c, req: Request, res: Response) =>\n res\n .status(500)\n .json({ err: `'${req.method} ${req.path}' not implemented` }),\n },\n });\n\n const templateRef = config.getOptionalString('bulkImport.importTemplate');\n let finalTemplateRef: string | undefined;\n if (templateRef) {\n finalTemplateRef = getImportTemplateRef(templateRef);\n }\n\n const orchestratorWorkflowId = config.getOptionalString(\n 'bulkImport.orchestratorWorkflow',\n );\n\n await api.init();\n\n api.register(\n Operations.PING,\n async (_c: Context, _req: Request, res: Response) => {\n const result = await ping(logger);\n return res.status(result.statusCode).json(result.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ALL_SCM_HOSTS,\n async (_c: Context, _req: Request, res: Response) => {\n const result = await findAllSCMHosts(config);\n return res.status(result.statusCode).json(result.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ALL_ORGANIZATIONS,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindAllOrganizations.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n q.pagePerIntegration = stringToNumber(q.pagePerIntegration);\n q.sizePerIntegration = stringToNumber(q.sizePerIntegration);\n const response = await findAllOrganizations(\n logger,\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n q.search,\n q.pagePerIntegration,\n q.sizePerIntegration,\n );\n return res.status(response.statusCode).json({\n errors: response.responseBody?.errors,\n organizations: response.responseBody?.organizations,\n totalCount: response.responseBody?.totalCount,\n pagePerIntegration: response.responseBody?.pagePerIntegration,\n sizePerIntegration: response.responseBody?.sizePerIntegration,\n approvalTool: q.approvalTool,\n } as Components.Schemas.OrganizationList);\n },\n );\n\n api.register(\n Operations.FIND_ALL_REPOSITORIES,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindAllRepositories.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n q.pagePerIntegration = stringToNumber(q.pagePerIntegration);\n q.sizePerIntegration = stringToNumber(q.sizePerIntegration);\n q.checkImportStatus = stringToBoolean(q.checkImportStatus);\n\n const userTokens = res.locals.scmTokens as\n Record<string, string> | undefined;\n\n if (!userTokens || Object.keys(userTokens).length === 0) {\n return res.status(401).json({\n error:\n 'User SCM credentials are required to list repositories. Ensure the SCM OAuth integration is configured.',\n });\n }\n\n const response = await findAllRepositories(\n {\n logger,\n config,\n gitApiService:\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n catalogHttpClient,\n },\n {\n search: q.search,\n checkStatus: q.checkImportStatus,\n pageNumber: q.pagePerIntegration,\n pageSize: q.sizePerIntegration,\n userTokens,\n },\n );\n const repos = response.responseBody?.repositories;\n return res.status(response.statusCode).json({\n errors: response.responseBody?.errors,\n repositories: repos,\n totalCount: response.responseBody?.totalCount,\n pagePerIntegration: q.pagePerIntegration,\n sizePerIntegration: q.sizePerIntegration,\n approvalTool: q.approvalTool,\n } as Components.Schemas.RepositoryList);\n },\n );\n\n api.register(\n Operations.FIND_REPOSITORIES_BY_ORGANIZATION,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindRepositoriesByOrganization.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n q.pagePerIntegration = stringToNumber(q.pagePerIntegration);\n q.sizePerIntegration = stringToNumber(q.sizePerIntegration);\n q.checkImportStatus = stringToBoolean(q.checkImportStatus);\n\n const userTokens = res.locals.scmTokens as\n Record<string, string> | undefined;\n\n if (!userTokens || Object.keys(userTokens).length === 0) {\n return res.status(401).json({\n error:\n 'User SCM credentials are required to list repositories. Ensure the SCM OAuth integration is configured.',\n });\n }\n\n const response = await findRepositoriesByOrganization(\n {\n logger,\n config,\n gitApiService:\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n catalogHttpClient,\n },\n c.request.params.organizationName?.toString(),\n q.search,\n q.checkImportStatus,\n q.pagePerIntegration,\n q.sizePerIntegration,\n userTokens,\n );\n const repos = response.responseBody?.repositories;\n return res.status(response.statusCode).json({\n errors: response.responseBody?.errors,\n repositories: repos,\n totalCount: response.responseBody?.totalCount,\n pagePerIntegration: q.pagePerIntegration,\n sizePerIntegration: q.sizePerIntegration,\n approvalTool: q.approvalTool,\n } as Components.Schemas.RepositoryList);\n },\n );\n\n api.register(\n Operations.FIND_ALL_IMPORTS,\n async (c: Context, _req: Request, res: Response) => {\n const {\n pageNumber,\n pageSize,\n apiVersion,\n search,\n sortColumn,\n sortOrder,\n } = getFindImportsParams(c);\n const response = await findAllImports(\n {\n logger,\n config,\n githubApiService,\n gitlabApiService,\n catalogHttpClient,\n },\n {\n apiVersion,\n },\n {\n search,\n pageNumber,\n pageSize,\n sortColumn,\n sortOrder,\n },\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n api.register(\n Operations.FIND_ALL_TASK_IMPORTS,\n async (c: Context, _req: Request, res: Response) => {\n const { pageNumber, pageSize, search, sortColumn, sortOrder } =\n getFindImportsParams(c);\n const imports: SourceImport[] = [];\n const repositories = await repositoryDao.findRepositories(\n pageNumber,\n pageSize,\n search,\n );\n\n for (const repo of repositories.data) {\n const response = await findTaskImportStatusByRepo(\n {\n logger,\n config,\n githubApiService,\n gitlabApiService,\n catalogHttpClient,\n repositoryDao,\n taskDao,\n taskLocationsDao,\n discovery,\n auth,\n },\n repo.url,\n true,\n );\n if (response.responseBody) {\n imports.push(response.responseBody);\n }\n }\n\n sortImports(imports, sortColumn, sortOrder);\n\n const responseBody: Components.Schemas.ImportJobListV2 = {\n imports,\n totalCount: repositories.total,\n page: pageNumber || 1,\n size: pageSize || 5,\n };\n\n return res.status(200).json(responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ALL_ORCHESTRATOR_WORKFLOW_IMPORTS,\n async (c: Context, req: Request, res: Response) => {\n const { pageNumber, pageSize, search, sortColumn, sortOrder } =\n getFindImportsParams(c);\n const imports: SourceImport[] = [];\n const repositories = await orchestratorRepositoryDao.findRepositories(\n pageNumber,\n pageSize,\n search,\n );\n\n for (const repo of repositories.data) {\n const response = await findOrchestratorImportStatusByRepo(\n {\n logger,\n orchestratorRepositoryDao,\n orchestratorWorkflowDao,\n discovery,\n auth,\n httpAuth,\n req,\n },\n repo.url,\n true,\n );\n if (response.responseBody) {\n imports.push(response.responseBody);\n }\n }\n\n sortImports(imports, sortColumn, sortOrder);\n\n const responseBody: Components.Schemas.ImportJobListV2 = {\n imports,\n totalCount: repositories.total,\n page: pageNumber || 1,\n size: pageSize || 5,\n };\n\n return res.status(200).json(responseBody);\n },\n );\n\n api.register(\n Operations.CREATE_IMPORT_JOBS,\n async (\n c: Context<Paths.CreateImportJobs.RequestBody>,\n _req: Request,\n res: Response,\n ) => {\n const q: Paths.CreateImportJobs.QueryParameters = {\n ...c.request.query,\n };\n q.dryRun = stringToBoolean(q.dryRun);\n const response = await createImportJobs(\n {\n logger,\n config,\n auth,\n gitlabApiService,\n githubApiService,\n catalogInfoGenerator,\n catalogHttpClient,\n },\n {\n importRequests: c.request.requestBody,\n dryRun: q.dryRun,\n },\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.CREATE_TASK_IMPORT_JOBS,\n async (\n c: Context<Paths.CreateImportJobs.RequestBody>,\n _req: Request,\n res: Response,\n ) => {\n if (!finalTemplateRef) {\n throw new Error(\n `Missing required config value: 'bulkImport.importTemplate'`,\n );\n }\n const response = await createTaskImportJobs(\n finalTemplateRef,\n discovery,\n logger,\n auth,\n config,\n repositoryDao,\n taskDao,\n taskLocationsDao,\n c.request.requestBody,\n githubApiService,\n );\n\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.CREATE_ORCHESTRATOR_WORKFLOW_JOBS,\n async (\n c: Context<Paths.CreateImportJobs.RequestBody>,\n req: Request,\n res: Response,\n ) => {\n if (!orchestratorWorkflowId) {\n throw new Error(\n `Missing required config value: 'bulkImport.orchestratorWorkflow'`,\n );\n }\n\n const response = await createWorkflowImportJobs({\n orchestratorWorkflowId,\n discovery,\n auth,\n httpAuth,\n req,\n requestBody: c.request.requestBody,\n orchestratorWorkflowDao,\n orchestratorRepositoryDao,\n githubApiService,\n gitlabApiService,\n });\n\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_TASK_IMPORT_STATUS_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindImportStatusByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank parameter');\n }\n const response = await findTaskImportStatusByRepo(\n {\n logger,\n config,\n githubApiService,\n gitlabApiService,\n catalogHttpClient,\n repositoryDao,\n taskDao,\n taskLocationsDao,\n discovery,\n auth,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_IMPORT_STATUS_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.FindImportStatusByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank parameter');\n }\n const response = await findImportStatusByRepo(\n {\n logger,\n config,\n gitApiService:\n q.approvalTool === 'GITLAB' ? gitlabApiService : githubApiService,\n catalogHttpClient,\n approvalTool: q.approvalTool,\n },\n q.repo,\n q.defaultBranch,\n true,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.FIND_ORCHESTRATOR_IMPORT_STATUS_BY_REPO,\n async (c: Context, req: Request, res: Response) => {\n const q: Paths.FindImportStatusByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank parameter');\n }\n const response = await findOrchestratorImportStatusByRepo(\n {\n logger,\n orchestratorRepositoryDao,\n orchestratorWorkflowDao,\n discovery,\n auth,\n httpAuth,\n req,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.DELETE_TASK_IMPORT_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.DeleteImportByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank \"repo\" parameter');\n }\n const response = await deleteRepositoryRecord(\n {\n logger,\n dao: repositoryDao,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.DELETE_IMPORT_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.DeleteImportByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank \"repo\" parameter');\n }\n const response = await deleteImportByRepo(\n {\n logger,\n config,\n gitApiService:\n parseGitURLForApprovalTool(q.repo) === 'GITLAB'\n ? gitlabApiService\n : githubApiService,\n catalogHttpClient,\n },\n q.repo,\n q.defaultBranch,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n api.register(\n Operations.DELETE_ORCHESTRATOR_IMPORT_BY_REPO,\n async (c: Context, _req: Request, res: Response) => {\n const q: Paths.DeleteImportByRepo.QueryParameters = {\n ...c.request.query,\n };\n if (!q.repo?.trim()) {\n throw new Error('missing or blank \"repo\" parameter');\n }\n const response = await deleteRepositoryRecord(\n {\n logger,\n dao: orchestratorRepositoryDao,\n },\n q.repo,\n );\n return res.status(response.statusCode).json(response.responseBody);\n },\n );\n\n const router = Router();\n router.use(express.json());\n\n // Strip x-scm-tokens from req.headers before the permission check and audit\n // middleware run so that OAuth tokens are never captured in audit logs.\n // The parsed map is stored in res.locals.scmTokens for handler use.\n router.use((req, res, next) => {\n const raw = req.headers['x-scm-tokens'];\n const rawStr = Array.isArray(raw) ? raw[0] : raw;\n delete req.headers['x-scm-tokens'];\n if (rawStr) {\n try {\n res.locals.scmTokens = parseScmTokensHeader(rawStr, logger);\n } catch (e) {\n next(e);\n return;\n }\n }\n next();\n });\n\n router.use(async (req, _res, next) => {\n if (req.path !== '/ping') {\n try {\n await permissionCheck(\n auditor,\n api.matchOperation(req as OpenAPIRequest)?.operationId,\n permissions,\n httpAuth,\n req,\n );\n } catch (e) {\n next(e);\n return;\n }\n }\n next();\n });\n\n router.use(async (req, res, next) => {\n const reqCast = req as OpenAPIRequest;\n const operationId = api.matchOperation(reqCast)?.operationId;\n\n const auditorEvent = await createAuditorEventByOperationId(\n operationId,\n req,\n auditor,\n );\n try {\n const response = (await api.handleRequest(reqCast, req, res)) as Response;\n auditorEvent?.success({ meta: { responseStatus: response.statusCode } });\n next();\n } catch (err: any) {\n auditorEvent?.fail({ error: err, meta: { responseStatus: 500 } });\n next(err);\n }\n });\n\n const middleware = MiddlewareFactory.create({ logger, config });\n router.use(middleware.error());\n\n return router;\n}\n\nasync function createAuditorEventByOperationId(\n operationId: string | undefined,\n req: Request,\n auditor: AuditorService,\n): Promise<AuditorServiceEvent | undefined> {\n let auditorEvent;\n switch (operationId) {\n case Operations.PING:\n auditorEvent = await auditCreateEvent(auditor, 'ping', req);\n break;\n case Operations.FIND_ALL_SCM_HOSTS:\n auditorEvent = await auditCreateEvent(auditor, 'scm-hosts-read', req);\n break;\n\n case Operations.FIND_ALL_ORGANIZATIONS:\n auditorEvent = await auditCreateEvent(auditor, 'org-read', req, {\n queryType: req.query.search ? 'by-query' : 'all',\n search: req.query?.search,\n });\n break;\n case Operations.FIND_ALL_REPOSITORIES:\n auditorEvent = await auditCreateEvent(auditor, 'repo-read', req, {\n queryType: req.query.search ? 'by-query' : 'all',\n search: req.query.search,\n });\n break;\n case Operations.FIND_REPOSITORIES_BY_ORGANIZATION: {\n const organizationName = req.params.organizationName?.toString();\n auditorEvent = await auditCreateEvent(auditor, 'repo-read', req, {\n queryType: 'by-org',\n organizationName,\n });\n break;\n }\n case Operations.FIND_ALL_IMPORTS:\n case Operations.FIND_ALL_TASK_IMPORTS:\n case Operations.FIND_ALL_ORCHESTRATOR_WORKFLOW_IMPORTS:\n auditorEvent = await auditCreateEvent(auditor, 'import-read', req, {\n queryType: req.query.search ? 'by-query' : 'all',\n search: req.query.search,\n });\n break;\n case Operations.CREATE_IMPORT_JOBS:\n case Operations.CREATE_TASK_IMPORT_JOBS:\n case Operations.CREATE_ORCHESTRATOR_WORKFLOW_JOBS:\n auditorEvent = await auditCreateEvent(auditor, 'import-write', req, {\n actionType: 'create',\n });\n break;\n case Operations.FIND_IMPORT_STATUS_BY_REPO:\n case Operations.FIND_TASK_IMPORT_STATUS_BY_REPO:\n case Operations.FIND_ORCHESTRATOR_IMPORT_STATUS_BY_REPO:\n auditorEvent = await auditCreateEvent(\n auditor,\n 'import-status-read',\n req,\n { queryType: 'by-query', repo: req.query.repo },\n );\n break;\n case Operations.DELETE_IMPORT_BY_REPO:\n case Operations.DELETE_TASK_IMPORT_BY_REPO:\n case Operations.DELETE_ORCHESTRATOR_IMPORT_BY_REPO:\n auditorEvent = await auditCreateEvent(auditor, 'import-write', req, {\n actionType: 'delete',\n repository: req.query.repo,\n });\n break;\n case undefined:\n auditorEvent = await auditCreateEvent(auditor, operationId, req);\n break;\n default:\n // do nothing\n break;\n }\n return auditorEvent;\n}\n\nfunction stringToNumber(s: number | undefined): number | undefined {\n return s ? Number.parseInt(s.toString(), 10) : undefined;\n}\n\nfunction stringToBoolean(s: boolean | undefined): boolean | undefined {\n if (!s) {\n return undefined;\n }\n return s.toString() === 'true';\n}\nfunction getFindImportsParams(c: Context<any, any, any, any, any, Document>): {\n pageNumber?: number;\n pageSize?: number;\n apiVersion?: Paths.FindAllImports.Parameters.ApiVersion;\n search?: string;\n sortColumn?: Components.Parameters.SortColumnQueryParam;\n sortOrder?: Components.Parameters.SortOrderQueryParam;\n} {\n const h: Paths.FindAllImports.HeaderParameters = {\n ...c.request.headers,\n };\n const apiVersion = h['api-version'];\n const q: Paths.FindAllImports.QueryParameters = {\n ...c.request.query,\n };\n // we need to convert strings to real types due to open PR https://github.com/openapistack/openapi-backend/pull/571\n let pageNumber: number | undefined;\n let pageSize: number | undefined;\n if (apiVersion === undefined || apiVersion === 'v1') {\n // pagePerIntegration and sizePerIntegration deprecated in v1. 'page' and 'size' take precedence.\n pageNumber = stringToNumber(q.page || q.pagePerIntegration);\n pageSize = stringToNumber(q.size || q.sizePerIntegration);\n } else {\n // pagePerIntegration and sizePerIntegration removed in v2+ and replaced by 'page' and 'size'.\n pageNumber = stringToNumber(q.page);\n pageSize = stringToNumber(q.size);\n }\n return {\n pageNumber,\n pageSize,\n apiVersion: apiVersion,\n search: q.search,\n sortColumn: q.sortColumn,\n sortOrder: q.sortOrder,\n };\n}\n"],"names":["Operations","InputError","auth","migrate","repositoryDao","RepositoryDao","ScaffolderTaskDao","TaskLocationsDao","OrchestratorWorkflowDao","githubApiService","GithubApiService","gitlabApiService","GitlabApiService","catalogHttpClient","CatalogHttpClient","catalogInfoGenerator","CatalogInfoGenerator","OpenAPIBackend","fullFormats","openApiDocument","getImportTemplateRef","ping","findAllSCMHosts","findAllOrganizations","findAllRepositories","findRepositoriesByOrganization","findAllImports","findTaskImportStatusByRepo","sortImports","findOrchestratorImportStatusByRepo","createImportJobs","createTaskImportJobs","createWorkflowImportJobs","findImportStatusByRepo","deleteRepositoryRecord","deleteImportByRepo","parseGitURLForApprovalTool","Router","express","permissionCheck","MiddlewareFactory","auditCreateEvent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,IAAU,UAAA;AAAA,CAAV,CAAUA,WAAAA,KAAV;AACS,EAAMA,YAAA,IAAA,GAAO,MAAA;AACb,EAAMA,YAAA,kBAAA,GAAqB,iBAAA;AAC3B,EAAMA,YAAA,sBAAA,GAAyB,sBAAA;AAC/B,EAAMA,YAAA,qBAAA,GAAwB,qBAAA;AAE9B,EAAMA,YAAA,iCAAA,GACX,gCAAA;AAEK,EAAMA,YAAA,gBAAA,GAAmB,gBAAA;AACzB,EAAMA,YAAA,qBAAA,GAAwB,oBAAA;AAC9B,EAAMA,YAAA,sCAAA,GACX,oCAAA;AAEK,EAAMA,YAAA,kBAAA,GAAqB,kBAAA;AAC3B,EAAMA,YAAA,uBAAA,GAA0B,sBAAA;AAChC,EAAMA,YAAA,iCAAA,GACX,gCAAA;AA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AI,CAAA;AAClC,IAAA,QAAA,GAAW,cAAA,CAAe,EAAE,IAAI,CAAA;AAAA,EAClC;AACA,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA,QAAQ,CAAA,CAAE,MAAA;AAAA,IACV,YAAY,CAAA,CAAE,UAAA;AAAA,IACd,WAAW,CAAA,CAAE;AAAA,GACf;AACF;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@red-hat-developer-hub/backstage-plugin-bulk-import-backend",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "9.0.1",
|
|
4
4
|
"main": "./dist/index.cjs.js",
|
|
5
5
|
"types": "./dist/index.d.ts",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -50,18 +50,18 @@
|
|
|
50
50
|
"openapi": "./scripts/openapi.sh"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@backstage/backend-defaults": "0.17.
|
|
54
|
-
"@backstage/backend-plugin-api": "^1.
|
|
55
|
-
"@backstage/catalog-model": "^1.
|
|
53
|
+
"@backstage/backend-defaults": "^0.17.8",
|
|
54
|
+
"@backstage/backend-plugin-api": "^1.10.0",
|
|
55
|
+
"@backstage/catalog-model": "^1.10.0",
|
|
56
56
|
"@backstage/config": "^1.3.8",
|
|
57
57
|
"@backstage/errors": "^1.3.1",
|
|
58
|
-
"@backstage/integration": "^2.
|
|
59
|
-
"@backstage/plugin-catalog-node": "^2.2.
|
|
60
|
-
"@backstage/plugin-permission-common": "^0.9.
|
|
58
|
+
"@backstage/integration": "^2.1.1",
|
|
59
|
+
"@backstage/plugin-catalog-node": "^2.2.4",
|
|
60
|
+
"@backstage/plugin-permission-common": "^0.9.10",
|
|
61
61
|
"@gitbeaker/rest": "^43.4.0",
|
|
62
62
|
"@octokit/auth-app": "^7.2.2",
|
|
63
63
|
"@octokit/rest": "^20.0.2",
|
|
64
|
-
"@red-hat-developer-hub/backstage-plugin-bulk-import-common": "^
|
|
64
|
+
"@red-hat-developer-hub/backstage-plugin-bulk-import-common": "^9.0.1",
|
|
65
65
|
"@red-hat-developer-hub/backstage-plugin-orchestrator-common": "^3.7.3",
|
|
66
66
|
"ajv-formats": "^3.0.1",
|
|
67
67
|
"eventsource-client": "^1.2.0",
|
|
@@ -74,11 +74,11 @@
|
|
|
74
74
|
"openapi-backend": "^5.10.6"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@backstage/backend-test-utils": "^1.11.
|
|
78
|
-
"@backstage/catalog-client": "^1.16.
|
|
79
|
-
"@backstage/cli": "^0.36.
|
|
77
|
+
"@backstage/backend-test-utils": "^1.11.6",
|
|
78
|
+
"@backstage/catalog-client": "^1.16.1",
|
|
79
|
+
"@backstage/cli": "^0.36.5",
|
|
80
80
|
"@backstage/config": "^1.3.8",
|
|
81
|
-
"@backstage/plugin-catalog-backend": "^3.
|
|
81
|
+
"@backstage/plugin-catalog-backend": "^3.9.1",
|
|
82
82
|
"@backstage/types": "^1.2.2",
|
|
83
83
|
"@openapitools/openapi-generator-cli": "2.40.1",
|
|
84
84
|
"@spotify/prettier-config": "^15.0.0",
|