Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add resolver that generates lockfile patch GitHub PRs #1132

Open
wants to merge 3 commits into
base: file-github-pr-cli
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ packageExtensions:
querystring: "*"
url: "*"
util: "*"
"@types/npm-registry-fetch@^8.0.4":
dependencies:
"@types/node-fetch": "*"
"node-fetch": "*"

"@types/serve-static@*":
dependencies:
mime: "*"
Expand Down
4 changes: 2 additions & 2 deletions lunatrace/bsl/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"generate:hasura-calls": "graphql-codegen --config codegen.hasura.yml",
"generate:custom-calls": "graphql-codegen --config codegen.lunatrace-custom.yml",
"generate:github-calls": "graphql-codegen --config codegen.github.yml",
"generate": "yarn run generate:github-calls && yarn run generate:hasura-calls && yarn run generate:custom-calls",
"generate": "echo 'Parallel running:' && echo github\nhasura\ncustom | xargs -I% -n 1 -P 5 sh -c 'echo \" yarn run generate:%-calls\" & yarn run generate:%-calls'",
"dev:graphql:watch": "yarn run generate:hasura-calls && watch 'yarn run generate:hasura-calls' ./src/hasura-api/graphql",
"compile": "tsc -p tsconfig.json && cp src/graphql-yoga/schema.graphql build/graphql-yoga/schema.graphql",
"compile:watch": "tsc -p tsconfig.json -w",
Expand All @@ -52,6 +52,7 @@
"@jest/globals": "~28.1.3",
"@lunatrace/logger": "workspace:~",
"@lunatrace/lunatrace-common": "workspace:~",
"@lunatrace/npm-package-cli": "workspace:~",
"@octokit/auth-app": "^3.6.1",
"@octokit/graphql": "^4.8.0",
"@octokit/plugin-rest-endpoint-methods": "^5.13.0",
Expand Down Expand Up @@ -85,7 +86,6 @@
"markdown-table": "2.0.0",
"minimatch": "~5.1.2",
"murmurhash-native": "^3.5.0",
"node-fetch": "2",
"nodemon": "^2.0.15",
"octokit": "^1.7.1",
"pg": "^8.7.1",
Expand Down
26 changes: 26 additions & 0 deletions lunatrace/bsl/backend/src/graphql-yoga/generated-resolver-types.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 5 additions & 8 deletions lunatrace/bsl/backend/src/graphql-yoga/helpers/auth-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,16 @@ export function getUserId(ctx: Context, kratos_id_instead = false): string {
return userId;
}

export async function checkProjectIsAuthorized(projectId: string, ctx: Context): Promise<void> {
const identityId = getUserId(ctx, true);
const usersAuthorizedProjects = await hasura.GetUsersProjects({ user_id: identityId });
const userIsAuthorized = usersAuthorizedProjects.projects.some((p) => {
return p.id === projectId;
});
if (!userIsAuthorized) {
export async function checkProjectIsAuthorizedOrThrow(projectId: string, ctx: Context): Promise<void> {
const identityId = getUserId(ctx);
const project = await hasura.GetUserProjectFromProjectId({ project_id: projectId, user_id: identityId });
if (project.projects.length === 0) {
throw new GraphQLYogaError('Not authorized for this project');
}
return;
}

export async function checkBuildsAreAuthorized(buildIds: string[], ctx: Context): Promise<void> {
export async function checkBuildsAreAuthorizedOrThrow(buildIds: string[], ctx: Context): Promise<void> {
const userId = getUserId(ctx);
const existingBuildsRes = await hasura.GetUsersBuilds({ build_ids: buildIds, user_id: userId });
if (!existingBuildsRes.builds) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/*
* Copyright by LunaSec (owned by Refinery Labs, Inc)
*
* Licensed under the Business Source License v1.1
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* https://github.com/lunasec-io/lunasec/blob/master/licenses/BSL-LunaTrace.txt
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { GraphQLYogaError } from '@graphql-yoga/node';
import {
PullRequestOctokit,
replacePackageAndFileGitHubPullRequest,
} from '@lunatrace/npm-package-cli/src/package/github-pr';

import { getInstallationAccessToken } from '../../github/auth';
import { hasura } from '../../hasura-api';
import { log } from '../../utils/log';
import { MutationResolvers } from '../generated-resolver-types';
import { checkProjectIsAuthorizedOrThrow, isAuthenticated } from '../helpers/auth-helpers';

type CreatePullRequestForVulnerabilityType = NonNullable<MutationResolvers['createPullRequestForVulnerability']>;

function splitGitHubRepoPath(gitHubRepo: string) {
const split = gitHubRepo.split('/');
freeqaz marked this conversation as resolved.
Show resolved Hide resolved
const owner = split[split.length - 2];
const repo = split[split.length - 1].replace('.git', '');
return { owner, repo };
}

/**
* Installs the repos the user selected in the GUIG
*/
export const createPullRequestForVulnerabilityResolver: CreatePullRequestForVulnerabilityType = async (
parent,
args,
ctx,
_info
) => {
try {
if (!isAuthenticated(ctx)) {
log.warn('No parsed JWT claims with a user ID on route that required authorization, throwing a graphql error');
throw new GraphQLYogaError('Unauthorized');
}

const vulnerabilityId = args.vulnerability_id;
if (!vulnerabilityId) {
throw new GraphQLYogaError('No vulnerability id provided');
}

const projectId = args.project_id;
if (!projectId) {
throw new GraphQLYogaError('No project id provided');
}

const oldPackageSlug = args.old_package_slug;
if (!oldPackageSlug) {
throw new GraphQLYogaError('No old package slug provided');
}

const newPackageSlug = args.new_package_slug;
if (!newPackageSlug) {
throw new GraphQLYogaError('No new package slug provided');
Copy link
Contributor

Choose a reason for hiding this comment

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

We could probably DRY up this to just be a param checking function that takes an array of property names as strings. I bet we could throw that in utils and call it a day.

Just a thought, not like an urgent change obv

}

const packageManifestPath = args.package_manifest_path;
if (!packageManifestPath) {
throw new GraphQLYogaError('No package manifest path provided');
}

// Strips out the actual package.json/yarn.lock/package-lock.json from the path since we just need the folder.
const normalizedPackageManifestPath = packageManifestPath
.replace(/package\.json$/, '')
.replace(/yarn\.lock$/, '')
.replace(/package-lock\.json$/, '');

await checkProjectIsAuthorizedOrThrow(projectId, ctx);

const installationIdResult = await hasura.GetGitHubInstallationIdFromProjectId({
project_id: projectId,
});

if (installationIdResult.projects.length === 0) {
throw new GraphQLYogaError('No project found when fetching installation id');
}

const installationId = installationIdResult.projects[0].organization?.installation_id;

if (!installationId) {
throw new GraphQLYogaError('No installation id found for project');
}

const githubRepo = installationIdResult.projects[0].github_repository?.git_url;

if (!githubRepo) {
throw new GraphQLYogaError('No github repo found for project');
}

const { owner, repo } = splitGitHubRepoPath(githubRepo);

const installationAccessTokenRes = await getInstallationAccessToken(installationId);
if (installationAccessTokenRes.error) {
log.error('Failed to fetch installation access token', { installationAccessTokenRes });
throw new Error('Error fetching installation access token');
}

const installationAccessToken = installationAccessTokenRes.res;

const octokit = new PullRequestOctokit({
auth: installationAccessToken,
});

const pullRequestResult = await replacePackageAndFileGitHubPullRequest(
octokit,
owner,
repo,
normalizedPackageManifestPath,
// TODO: Make this less hacky and brittle
packageManifestPath.endsWith('package-lock.json') ? 'npm' : 'yarn',
Copy link
Contributor

Choose a reason for hiding this comment

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

This is probably not a safe check. I think we should expand this into a function that throws if it doesnt look npm-y or yarn-y.

Pnpm exists, and so on and so forth. Bun too! haha

oldPackageSlug,
newPackageSlug
);

// TODO: Actually implement this endpoint instead of this stub
return {
success: true,
pullRequestUrl: pullRequestResult.pullRequestUrl,
};
} catch (error) {
// TODO: temporary error handler until i figure out how to deal with global errors in yoga which seems maybe impossible
Copy link
Contributor

Choose a reason for hiding this comment

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

It's impossible unless we drop yoga for apollo, or at least, difficult, i tried. we need to go to apollo anyway because yoga is just a sucky wrapper around apollo.

Apollo stinks but it at least has that part working.

You may as well wrap this unknown error in a nice graphqlError because yoga will catch it anyway, and return something nebulous to the client. So you might as well just throw new "GraphQLYogaError("An Unknown error occurred while attempting to update dependencies") I have it set up so those will render out to the user in an alert.

That way it at least looks better on the client

if (error instanceof GraphQLYogaError) {
log.warn('handled graphql yoga error, returning error to client', { error });
} else {
log.error('UNKNOWN ERROR IN GRAPHQL RESOLVER', { e: error });
}
throw error;
}
};
2 changes: 2 additions & 0 deletions lunatrace/bsl/backend/src/graphql-yoga/resolvers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Resolvers } from '../generated-resolver-types';

import { authenticatedRepoCloneUrlResolver } from './authenticated-repo-clone-url';
import { availableOrgsWithReposResolver } from './available-repos';
import { createPullRequestForVulnerabilityResolver } from './create-pull-request-for-vulnerability';
import { installSelectedReposResolver } from './install-selected-repos';
import { presignManifestUploadResolver } from './presign-manifest-upload';
import { presignSbomUploadResolver } from './presign-sbom-upload';
Expand All @@ -34,6 +35,7 @@ export const resolvers: Resolvers = {
Mutation: {
presignManifestUpload: presignManifestUploadResolver,
installSelectedRepos: installSelectedReposResolver,
createPullRequestForVulnerability: createPullRequestForVulnerabilityResolver,
},
uuid: GraphQLUUID,
jsonb: GraphQLJSON,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { v4 as uuid } from 'uuid';
import { getBackendBucketConfig } from '../../config';
import { aws } from '../../utils/aws-utils';
import { MutationResolvers } from '../generated-resolver-types';
import { checkProjectIsAuthorized, throwIfUnauthenticated } from '../helpers/auth-helpers';
import { checkProjectIsAuthorizedOrThrow, throwIfUnauthenticated } from '../helpers/auth-helpers';

type PresignManifestUploadResolver = NonNullable<MutationResolvers['presignManifestUpload']>;

Expand All @@ -26,7 +26,7 @@ const sbomHandlerConfig = getBackendBucketConfig();
export const presignManifestUploadResolver: PresignManifestUploadResolver = async (parent, args, ctx, info) => {
throwIfUnauthenticated(ctx);
const projectId = args.project_id;
await checkProjectIsAuthorized(projectId, ctx);
await checkProjectIsAuthorizedOrThrow(projectId, ctx);
const today = new Date();
const uniqueId = uuid();

Expand Down
4 changes: 2 additions & 2 deletions lunatrace/bsl/backend/src/graphql-yoga/resolvers/sbom-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ import { hasura } from '../../hasura-api';
import { aws } from '../../utils/aws-utils';
import { log } from '../../utils/log';
import { QueryResolvers } from '../generated-resolver-types';
import { checkProjectIsAuthorized, throwIfUnauthenticated } from '../helpers/auth-helpers';
import { checkProjectIsAuthorizedOrThrow, throwIfUnauthenticated } from '../helpers/auth-helpers';

type sbomUrlResolverT = NonNullable<QueryResolvers['sbomUrl']>;

export const sbomUrlResolver: sbomUrlResolverT = async (parent, args, ctx, info) => {
throwIfUnauthenticated(ctx);
const build = await hasura.GetBuild({ build_id: args.buildId });
await checkProjectIsAuthorized(build.builds_by_pk?.project?.id, ctx);
await checkProjectIsAuthorizedOrThrow(build.builds_by_pk?.project?.id, ctx);

try {
return formatUrl(await aws.signArbitraryS3URL(build.builds_by_pk?.s3_url || '', 'GET'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ import { SeverityNamesOsv, severityOrderOsv } from '@lunatrace/lunatrace-common'
import { loadTree } from '../../models/vulnerability-dependency-tree/load-tree';
import { log } from '../../utils/log';
import { QueryResolvers } from '../generated-resolver-types';
import { checkBuildsAreAuthorized, throwIfUnauthenticated } from '../helpers/auth-helpers';
import { checkBuildsAreAuthorizedOrThrow, throwIfUnauthenticated } from '../helpers/auth-helpers';

type BuildVulnerabilitiesResolver = NonNullable<QueryResolvers['vulnerableReleasesFromBuild']>;

export const vulnerableReleasesFromBuildResolver: BuildVulnerabilitiesResolver = async (parent, args, ctx, info) => {
throwIfUnauthenticated(ctx);
const buildId = args.buildId;
await checkBuildsAreAuthorized([buildId], ctx);
await checkBuildsAreAuthorizedOrThrow([buildId], ctx);

const logger = log.child('vulnerable-releases-resolver', { buildId });

Expand Down
13 changes: 13 additions & 0 deletions lunatrace/bsl/backend/src/graphql-yoga/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ type Mutation {
installSelectedRepos(
orgs: [OrgsWithReposInput!]!
): InstallSelectedReposResponse
createPullRequestForVulnerability(
project_id: uuid!
vulnerability_id: uuid!
""" We could pull this data from the database, probably, but it's easier to pass it in from the Frontend """
old_package_slug: String!
new_package_slug: String!
package_manifest_path: String!
): CreatePullRequestForVulnerabilityResponse
}

input OrgsWithReposInput {
Expand All @@ -37,6 +45,11 @@ type InstallSelectedReposResponse {
success: Boolean
}

type CreatePullRequestForVulnerabilityResponse {
success: Boolean
pullRequestUrl: String!
}

input SbomUploadUrlInput {
orgId: uuid!
projectId: uuid!
Expand Down
Loading