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 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
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,
}
26 changes: 16 additions & 10 deletions site/src/components/WorkspaceSchedule/WorkspaceSchedule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,13 @@ 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 +66,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 @@ -16,6 +16,11 @@ const THIRTY = 30
export default {
title: "components/WorkspaceScheduleButton",
component: WorkspaceScheduleButton,
argTypes: {
canUpdateWorkspace: {
defaultValue: true,
},
},
}

const Template: Story<WorkspaceScheduleButtonProps> = (args) => (
Expand Down Expand Up @@ -115,3 +120,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,
}
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
56 changes: 42 additions & 14 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: "You don't have permissions to update the schedule for this workspace.",
}

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 @@ -153,20 +168,31 @@ export const WorkspaceSchedulePage: React.FC = () => {
if (!username || !workspaceName) {
navigate("/workspaces")
return null
} else if (
}

if (
scheduleState.matches("idle") ||
scheduleState.matches("gettingWorkspace") ||
scheduleState.matches("gettingPermissions") ||
!workspace
) {
return <FullScreenLoader />
} else if (scheduleState.matches("error")) {
}

if (scheduleState.matches("error")) {
return (
<ErrorSummary
error={getWorkspaceError}
error={getWorkspaceError || checkPermissionsError}
retry={() => scheduleSend({ type: "GET_WORKSPACE", username, workspaceName })}
/>
)
} else if (scheduleState.matches("presentForm") || scheduleState.matches("submittingSchedule")) {
}

if (!permissions?.updateWorkspace) {
return <ErrorSummary error={Error(Language.forbiddenError)} />
}

if (scheduleState.matches("presentForm") || scheduleState.matches("submittingSchedule")) {
return (
<WorkspaceScheduleForm
fieldErrors={formErrors}
Expand All @@ -184,13 +210,15 @@ export const WorkspaceSchedulePage: React.FC = () => {
}}
/>
)
} else if (scheduleState.matches("submitSuccess")) {
}

if (scheduleState.matches("submitSuccess")) {
navigate(`/@${username}/${workspaceName}`)
return <FullScreenLoader />
} else {
// Theoretically impossible - log and bail
console.error("WorkspaceSchedulePage: unknown state :: ", scheduleState)
navigate("/")
return null
}

// Theoretically impossible - log and bail
Copy link
Member

Choose a reason for hiding this comment

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

Potentially unpopular opinion up for debate: I think I'd rather the user run into an error state here so I know we've reached the 'theoretically impossible' state and we have a bug on their hands.

Copy link
Contributor Author

@AbhineetJain AbhineetJain Jul 1, 2022

Choose a reason for hiding this comment

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

I think we should still provide our users a way to get out of the error state. For example, in this case we are just redirecting to /. Maybe we can show them a generic error like "This should not have happened. Go to workspaces."

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Additionally, we can also show them the Report an issue link opening in new tab.

console.error("WorkspaceSchedulePage: unknown state :: ", scheduleState)
navigate("/")
return null
}
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