Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 2 additions & 1 deletion 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
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.

Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,9 @@ export function getUserId(ctx: Context, kratos_id_instead = false): string {
}

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) {
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;
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 { checkProjectIsAuthorized, isAuthenticated } from '../helpers/auth-helpers';

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

function splitGitHubRepoPath(gitHubRepo: string) {
const split = gitHubRepo.split('/');
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 checkProjectIsAuthorized(projectId, ctx);
Copy link
Contributor

Choose a reason for hiding this comment

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

can you leave a comment that this will throw on error? I find it confusing to have a line of code whose side effect is not clear.

Copy link
Member Author

Choose a reason for hiding this comment

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

I renamed the function so that this is consistent everywhere in the repo.


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
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