Skip to content

fix: restrict edit schedule access #2698

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

Merged
merged 6 commits into from
Jul 1, 2022
Merged
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
Next Next commit
fix: restrict edit schedule access
  • Loading branch information
AbhineetJain committed Jul 1, 2022
commit f54127347b637a4be228fbf893aace4b48ca345c
1 change: 1 addition & 0 deletions site/src/components/Workspace/Workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export const Workspace: FC<WorkspaceProps> = ({
workspace={workspace}
onDeadlineMinus={scheduleProps.onDeadlineMinus}
onDeadlinePlus={scheduleProps.onDeadlinePlus}
canUpdateWorkspace={canUpdateWorkspace}
/>
<WorkspaceActions
workspace={workspace}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ const THIRTY = 30
export default {
title: "components/WorkspaceSchedule",
component: WorkspaceSchedule,
argTypes: {
canUpdateWorkspace: {
defaultValue: true,
},
},
}

const Template: Story<WorkspaceScheduleProps> = (args) => <WorkspaceSchedule {...args} />
Expand All @@ -40,7 +45,7 @@ NoTTL.args = {
...Mocks.MockWorkspace,
latest_build: {
...Mocks.MockWorkspaceBuild,
// a mannual shutdown has a deadline of '"0001-01-01T00:00:00Z"'
// a manual shutdown has a deadline of '"0001-01-01T00:00:00Z"'
// SEE: #1834
deadline: "0001-01-01T00:00:00Z",
},
Expand Down Expand Up @@ -113,3 +118,17 @@ WorkspaceOffLong.args = {
ttl_ms: 2 * 365 * 24 * 60 * 60 * 1000, // 2 years
},
}

export const CannotEdit = Template.bind({})
CannotEdit.args = {
workspace: {
...Mocks.MockWorkspace,

latest_build: {
...Mocks.MockWorkspaceBuild,
transition: "stop",
},
ttl_ms: 2 * 60 * 60 * 1000, // 2 hours
},
canUpdateWorkspace: false,
}
23 changes: 13 additions & 10 deletions site/src/components/WorkspaceSchedule/WorkspaceSchedule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ export const Language = {

export interface WorkspaceScheduleProps {
workspace: Workspace
canUpdateWorkspace: boolean
}

export const WorkspaceSchedule: FC<WorkspaceScheduleProps> = ({ workspace }) => {
export const WorkspaceSchedule: FC<WorkspaceScheduleProps> = ({ workspace, canUpdateWorkspace }) => {
const styles = useStyles()
const timezone = workspace.autostart_schedule
? extractTimezone(workspace.autostart_schedule)
Expand All @@ -62,15 +63,17 @@ export const WorkspaceSchedule: FC<WorkspaceScheduleProps> = ({ workspace }) =>
</span>
</Stack>
</div>
<div>
<Link
className={styles.scheduleAction}
component={RouterLink}
to={`/@${workspace.owner_name}/${workspace.name}/schedule`}
>
{Language.editScheduleLink}
</Link>
</div>
{canUpdateWorkspace && (
<div>
<Link
className={styles.scheduleAction}
component={RouterLink}
to={`/@${workspace.owner_name}/${workspace.name}/schedule`}
>
{Language.editScheduleLink}
</Link>
</div>
)}
</Stack>
</div>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,14 @@ export interface WorkspaceScheduleButtonProps {
workspace: Workspace
onDeadlinePlus: () => void
onDeadlineMinus: () => void
canUpdateWorkspace: boolean
}

export const WorkspaceScheduleButton: React.FC<WorkspaceScheduleButtonProps> = ({
workspace,
onDeadlinePlus,
onDeadlineMinus,
canUpdateWorkspace,
}) => {
const anchorRef = useRef<HTMLButtonElement>(null)
const [isOpen, setIsOpen] = useState(false)
Expand All @@ -74,7 +76,7 @@ export const WorkspaceScheduleButton: React.FC<WorkspaceScheduleButtonProps> = (
<div className={styles.wrapper}>
<div className={styles.label}>
<WorkspaceScheduleLabel workspace={workspace} />
{shouldDisplayPlusMinus(workspace) && (
{canUpdateWorkspace && shouldDisplayPlusMinus(workspace) && (
<Stack direction="row" spacing={0}>
<IconButton
className={styles.iconButton}
Expand Down Expand Up @@ -124,7 +126,7 @@ export const WorkspaceScheduleButton: React.FC<WorkspaceScheduleButtonProps> = (
horizontal: "right",
}}
>
<WorkspaceSchedule workspace={workspace} />
<WorkspaceSchedule workspace={workspace} canUpdateWorkspace={canUpdateWorkspace} />
</Popover>
</div>
</div>
Expand Down
28 changes: 23 additions & 5 deletions site/src/pages/WorkspaceSchedulePage/WorkspaceSchedulePage.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useMachine } from "@xstate/react"
import { useMachine, useSelector } from "@xstate/react"
import * as cronParser from "cron-parser"
import dayjs from "dayjs"
import timezone from "dayjs/plugin/timezone"
import utc from "dayjs/plugin/utc"
import React, { useEffect } from "react"
import React, { useContext, useEffect } from "react"
import { useNavigate, useParams } from "react-router-dom"
import * as TypesGen from "../../api/typesGenerated"
import { ErrorSummary } from "../../components/ErrorSummary/ErrorSummary"
Expand All @@ -16,6 +16,8 @@ import {
} from "../../components/WorkspaceScheduleForm/WorkspaceScheduleForm"
import { firstOrItem } from "../../util/array"
import { extractTimezone, stripTimezone } from "../../util/schedule"
import { selectUser } from "../../xServices/auth/authSelectors"
import { XServiceContext } from "../../xServices/StateContext"
import { workspaceSchedule } from "../../xServices/workspaceSchedule/workspaceScheduleXService"

// REMARK: timezone plugin depends on UTC
Expand All @@ -24,6 +26,10 @@ import { workspaceSchedule } from "../../xServices/workspaceSchedule/workspaceSc
dayjs.extend(utc)
dayjs.extend(timezone)

const Language = {
forbiddenError: "403: Workspace schedule update forbidden.",
}

export const formValuesToAutoStartRequest = (
values: WorkspaceScheduleFormValues,
): TypesGen.UpdateWorkspaceAutostartRequest => {
Expand Down Expand Up @@ -141,8 +147,17 @@ export const WorkspaceSchedulePage: React.FC = () => {
const navigate = useNavigate()
const username = firstOrItem(usernameQueryParam, null)
const workspaceName = firstOrItem(workspaceQueryParam, null)
const [scheduleState, scheduleSend] = useMachine(workspaceSchedule)
const { formErrors, getWorkspaceError, workspace } = scheduleState.context

const xServices = useContext(XServiceContext)
const me = useSelector(xServices.authXService, selectUser)

const [scheduleState, scheduleSend] = useMachine(workspaceSchedule, {
context: {
userId: me?.id,
},
})
const { checkPermissionsError, formErrors, getWorkspaceError, permissions, workspace } =
scheduleState.context

// Get workspace on mount and whenever the args for getting a workspace change.
// scheduleSend should not change.
Expand All @@ -156,16 +171,19 @@ export const WorkspaceSchedulePage: React.FC = () => {
} else if (
scheduleState.matches("idle") ||
scheduleState.matches("gettingWorkspace") ||
scheduleState.matches("gettingPermissions") ||
!workspace
) {
return <FullScreenLoader />
} else if (scheduleState.matches("error")) {
return (
<ErrorSummary
error={getWorkspaceError}
error={getWorkspaceError || checkPermissionsError}
retry={() => scheduleSend({ type: "GET_WORKSPACE", username, workspaceName })}
/>
)
} else if (!permissions?.updateWorkspace) {
return <ErrorSummary error={Error(Language.forbiddenError)} />
} else if (scheduleState.matches("presentForm") || scheduleState.matches("submittingSchedule")) {
return (
<WorkspaceScheduleForm
Expand Down
64 changes: 62 additions & 2 deletions site/src/xServices/workspaceSchedule/workspaceScheduleXService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export const Language = {
successMessage: "Successfully updated workspace schedule.",
}

type Permissions = Record<keyof ReturnType<typeof permissionsToCheck>, boolean>

export interface WorkspaceScheduleContext {
formErrors?: FieldErrors
getWorkspaceError?: Error | unknown
Expand All @@ -23,8 +25,27 @@ export interface WorkspaceScheduleContext {
* machine is partially influenced by workspaceXService.
*/
workspace?: TypesGen.Workspace
// permissions
userId?: string
permissions?: Permissions
checkPermissionsError?: Error | unknown
}

export const checks = {
updateWorkspace: "updateWorkspace",
} as const

const permissionsToCheck = (workspace: TypesGen.Workspace) => ({
[checks.updateWorkspace]: {
object: {
resource_type: "workspace",
resource_id: workspace.id,
owner_id: workspace.owner_id,
},
action: "update",
},
})

export type WorkspaceScheduleEvent =
| { type: "GET_WORKSPACE"; username: string; workspaceName: string }
| {
Expand Down Expand Up @@ -60,7 +81,7 @@ export const workspaceSchedule = createMachine(
src: "getWorkspace",
id: "getWorkspace",
onDone: {
target: "presentForm",
target: "gettingPermissions",
actions: ["assignWorkspace"],
},
onError: {
Expand All @@ -70,6 +91,25 @@ export const workspaceSchedule = createMachine(
},
tags: "loading",
},
gettingPermissions: {
entry: "clearGetPermissionsError",
invoke: {
src: "checkPermissions",
id: "checkPermissions",
onDone: [
{
actions: ["assignPermissions"],
target: "presentForm",
},
],
onError: [
{
actions: "assignGetPermissionsError",
target: "error",
},
],
},
},
presentForm: {
on: {
SUBMIT_SCHEDULE: "submittingSchedule",
Expand Down Expand Up @@ -113,8 +153,19 @@ export const workspaceSchedule = createMachine(
assignGetWorkspaceError: assign({
getWorkspaceError: (_, event) => event.data,
}),
assignPermissions: assign({
// Setting event.data as Permissions to be more stricted. So we know
// what permissions we asked for.
permissions: (_, event) => event.data as Permissions,
}),
assignGetPermissionsError: assign({
checkPermissionsError: (_, event) => event.data,
}),
clearGetPermissionsError: assign({
checkPermissionsError: (_) => undefined,
}),
clearContext: () => {
assign({ workspace: undefined })
assign({ workspace: undefined, permissions: undefined })
},
clearGetWorkspaceError: (context) => {
assign({ ...context, getWorkspaceError: undefined })
Expand All @@ -134,6 +185,15 @@ export const workspaceSchedule = createMachine(
getWorkspace: async (_, event) => {
return await API.getWorkspaceByOwnerAndName(event.username, event.workspaceName)
},
checkPermissions: async (context) => {
if (context.workspace && context.userId) {
return await API.checkUserPermissions(context.userId, {
checks: permissionsToCheck(context.workspace),
})
} else {
throw Error("Cannot check permissions without both workspace and user id")
}
},
submitSchedule: async (context, event) => {
if (!context.workspace?.id) {
// This state is theoretically impossible, but helps TS
Expand Down