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

fix: Add creator_id into CreateFlow mutation #826

Closed
wants to merge 3 commits into from
Closed
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
46 changes: 22 additions & 24 deletions editor.planx.uk/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { render } from "react-dom";
import { NotFoundBoundary, Router, useLoadingRoute, View } from "react-navi";
import HelmetProvider from "react-navi-helmet-async";
import { ToastContainer } from "react-toastify";
import { RoutingContext } from "routes";

import DelayedLoadingIndicator from "./components/DelayedLoadingIndicator";
import { client } from "./lib/graphql";
Expand All @@ -27,30 +28,27 @@ if (!window.customElements.get("my-map")) {
window.customElements.define("my-map", MyMap);
}

const hasJWT = (): boolean | void => {
let jwt = getCookie("jwt");
if (jwt) {
try {
if (
Number(
(jwtDecode(jwt) as any)["https://hasura.io/jwt/claims"][
"x-hasura-user-id"
]
) > 0
) {
return true;
}
} catch (e) {}
const setJWTCookieFromQueryParams = (): void => {
const jwt = new URLSearchParams(window.location.search).get("jwt");
if (!jwt) return;
// Set the JWT, and remove it from the url
setCookie("jwt", jwt);
window.location.href = "/";
};

const getContextFromJWT = (): RoutingContext | undefined => {
const jwt = getCookie("jwt") || setJWTCookieFromQueryParams();
// Re-run this function if we did not get the JWT from the cookie
if (!jwt) return;
try {
const userId = Number(
(jwtDecode(jwt!) as any)["https://hasura.io/jwt/claims"][
"x-hasura-user-id"
]
);
return { currentUser: { userId } };
} catch (e) {
window.location.href = "/logout";
} else {
jwt = new URLSearchParams(window.location.search).get("jwt");
if (jwt) {
setCookie("jwt", jwt);
// set the jwt, and remove it from the url, then re-run this function
window.location.href = "/";
} else {
return false;
}
}
};

Expand All @@ -74,7 +72,7 @@ const Layout: React.FC<{
render(
<>
<ApolloProvider client={client}>
<Router context={{ currentUser: hasJWT() }} navigation={navigation}>
<Router context={getContextFromJWT()} navigation={navigation}>
<HelmetProvider>
<Layout>
<CssBaseline />
Expand Down
20 changes: 16 additions & 4 deletions editor.planx.uk/src/pages/FlowEditor/lib/store/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export interface EditorStore extends Store.Store {
connect: (src: Store.nodeId, tgt: Store.nodeId, object?: any) => void;
connectTo: (id: Store.nodeId) => void;
copyNode: (id: Store.nodeId) => void;
createFlow: (teamId: any, newSlug: any) => Promise<string>;
createFlow: (teamId: any, newSlug: any, creatorId: number) => Promise<string>;
deleteFlow: (teamId: number, flowSlug: string) => Promise<object>;
diffFlow: (flowId: string) => Promise<any>;
getFlows: (teamId: number) => Promise<any>;
Expand Down Expand Up @@ -145,13 +145,24 @@ export const editorStore = (
localStorage.setItem("clipboard", id);
},

createFlow: async (teamId, newSlug) => {
createFlow: async (teamId, newSlug, creatorId) => {
const data = { [ROOT_NODE_KEY]: { edges: [] } };
let response = (await client.mutate({
mutation: gql`
mutation CreateFlow($data: jsonb, $slug: String, $teamId: Int) {
mutation CreateFlow(
$data: jsonb
$slug: String
$teamId: Int
$creatorId: Int
) {
insert_flows_one(
object: { data: $data, slug: $slug, team_id: $teamId, version: 1 }
object: {
data: $data
slug: $slug
team_id: $teamId
version: 1
creator_id: $creatorId
Copy link
Contributor

@johnrees johnrees Jan 28, 2022

Choose a reason for hiding this comment

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

I think there might be a bit of a security issue here that could get flagged by a security audit in future. It might be that we can ignore it for the time being though*

The issue is - a user could potentially set any creator_id they wanted with some sneaky frontend code tweaking, or by looking at the network request and then replaying it with a different creator_id of their choosing.

The way around it would be to extract the x-hasura-user-id from the JWT in hasura itself, so in the hasura console, you'd set creator_id to have the default value of x-hasura-user-id and have permissions so that creator_id can't be overridden.

https://hasura.io/docs/latest/graphql/core/databases/postgres/schema/default-values/column-presets.html#step-1-configure-a-column-preset

e.g.
Screenshot 2022-01-28 at 2 14 38 AM

Doing that should mean that it's impossible for someone to spoof the creator_id.

* However, IIRC we've all got full admin permissions right now anyway, which is why I think we might have bigger problems than this if we had an audit soon. Hmm 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's very helpful feedback thanks - I'll take a crack at this approach.

}
) {
id
data
Expand All @@ -162,6 +173,7 @@ export const editorStore = (
slug: newSlug,
teamId,
data,
creatorId,
},
})) as any;

Expand Down
5 changes: 3 additions & 2 deletions editor.planx.uk/src/pages/Team.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import DeleteOutline from "@material-ui/icons/DeleteOutline";
import FolderOutlined from "@material-ui/icons/FolderOutlined";
import formatDistanceToNow from "date-fns/formatDistanceToNow";
import React, { useCallback, useEffect, useState } from "react";
import { Link, useNavigation } from "react-navi";
import { Link, useCurrentRoute, useNavigation } from "react-navi";
import { slugify } from "utils";

import { client } from "../lib/graphql";
Expand Down Expand Up @@ -307,6 +307,7 @@ const Team: React.FC<{ id: number; slug: string }> = ({ id, slug }) => {
useEffect(() => {
fetchFlows();
}, [fetchFlows]);
const creatorId = useCurrentRoute().data?.currentUser?.userId;
return (
<Box className={classes.root}>
<Box className={classes.dashboard}>
Expand Down Expand Up @@ -337,7 +338,7 @@ const Team: React.FC<{ id: number; slug: string }> = ({ id, slug }) => {
const newFlowSlug = slugify(newFlowName);
useStore
.getState()
.createFlow(id, newFlowSlug)
.createFlow(id, newFlowSlug, creatorId)
.then((newId: string) => {
navigation.navigate(`/${slug}/${newId}`);
});
Expand Down
3 changes: 2 additions & 1 deletion editor.planx.uk/src/routes/authenticated.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import Teams from "../pages/Teams";
import { makeTitle } from "./utils";

const editorRoutes = compose(
withData((req) => ({
withData((req, context) => ({
// just putting anything here for now
username: "A",
...context,
})),

withView(() => <AuthenticatedLayout />),
Expand Down
10 changes: 6 additions & 4 deletions editor.planx.uk/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import Login from "../pages/Login";
import NetworkError from "../pages/NetworkError";
import { makeTitle } from "./utils";

type RoutingContext = {
currentUser?: any;
export type RoutingContext = {
currentUser?: {
userId: number;
};
};

const editorRoutes = mount({
Expand All @@ -17,7 +19,7 @@ const editorRoutes = mount({
}),

"/login": map(async (req, context: RoutingContext) =>
context.currentUser
Boolean(context.currentUser?.userId)
? redirect(
req.params.redirectTo
? decodeURIComponent(req.params.redirectTo)
Expand Down Expand Up @@ -48,7 +50,7 @@ const editorRoutes = mount({
}),

"*": map(async (req, context: RoutingContext) =>
context.currentUser
Boolean(context.currentUser?.userId)
? lazy(() => import("./authenticated"))
: redirect(`/login/?redirectTo=${encodeURIComponent(req.originalUrl)}`, {
exact: false,
Expand Down