Skip to content

feat: Allow admins to access member workspace terminals #2114

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 5 commits into from
Jun 10, 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 coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ func New(options *Options) *API {
r.Use(
apiKeyMiddleware,
httpmw.ExtractWorkspaceAgentParam(options.Database),
httpmw.ExtractWorkspaceParam(options.Database),
)
r.Get("/", api.workspaceAgent)
r.Get("/dial", api.workspaceAgentDial)
Expand Down
16 changes: 13 additions & 3 deletions coderd/coderd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,7 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
"GET:/api/v2/workspaceagents/me/listen": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/me/metadata": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/me/turn": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/{workspaceagent}": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/{workspaceagent}/dial": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/{workspaceagent}/iceservers": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/{workspaceagent}/pty": {NoAuthorize: true},
"GET:/api/v2/workspaceagents/{workspaceagent}/turn": {NoAuthorize: true},

// These endpoints have more assertions. This is good, add more endpoints to assert if you can!
Expand Down Expand Up @@ -210,6 +207,18 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
AssertAction: rbac.ActionRead,
AssertObject: workspaceRBACObj,
},
"GET:/api/v2/workspaceagents/{workspaceagent}": {
AssertAction: rbac.ActionRead,
AssertObject: workspaceRBACObj,
},
"GET:/api/v2/workspaceagents/{workspaceagent}/dial": {
AssertAction: rbac.ActionUpdate,
AssertObject: workspaceRBACObj,
},
"GET:/api/v2/workspaceagents/{workspaceagent}/pty": {
AssertAction: rbac.ActionUpdate,
AssertObject: workspaceRBACObj,
},
"GET:/api/v2/workspaces/": {
StatusCode: http.StatusOK,
AssertAction: rbac.ActionRead,
Expand Down Expand Up @@ -378,6 +387,7 @@ func TestAuthorizeAllEndpoints(t *testing.T) {
route = strings.ReplaceAll(route, "{workspacebuild}", workspace.LatestBuild.ID.String())
route = strings.ReplaceAll(route, "{workspacename}", workspace.Name)
route = strings.ReplaceAll(route, "{workspacebuildname}", workspace.LatestBuild.Name)
route = strings.ReplaceAll(route, "{workspaceagent}", workspaceResources[0].Agents[0].ID.String())
route = strings.ReplaceAll(route, "{template}", template.ID.String())
route = strings.ReplaceAll(route, "{hash}", file.Hash)
route = strings.ReplaceAll(route, "{workspaceresource}", workspaceResources[0].ID.String())
Expand Down
4 changes: 2 additions & 2 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ type userRolesKey struct{}
// AuthorizationUserRoles returns the roles used for authorization.
// Comes from the ExtractAPIKey handler.
func AuthorizationUserRoles(r *http.Request) database.GetAuthorizationUserRolesRow {
apiKey, ok := r.Context().Value(userRolesKey{}).(database.GetAuthorizationUserRolesRow)
userRoles, ok := r.Context().Value(userRolesKey{}).(database.GetAuthorizationUserRolesRow)
if !ok {
panic("developer error: user roles middleware not provided")
}
return apiKey
return userRoles
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixing previous debt!

}

// OAuth2Configs is a collection of configurations for OAuth-based authentication.
Expand Down
19 changes: 3 additions & 16 deletions coderd/httpmw/workspaceagentparam.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"errors"
"net/http"

"github.com/go-chi/chi/v5"

"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/httpapi"
)
Expand Down Expand Up @@ -74,24 +76,9 @@ func ExtractWorkspaceAgentParam(db database.Store) func(http.Handler) http.Handl
})
return
}
workspace, err := db.GetWorkspaceByID(r.Context(), build.WorkspaceID)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: "Internal error fetching workspace.",
Detail: err.Error(),
})
return
}

apiKey := APIKey(r)
if apiKey.UserID != workspace.OwnerID {
httpapi.Write(rw, http.StatusUnauthorized, httpapi.Response{
Message: "Getting non-personal agents isn't supported.",
})
return
}

ctx := context.WithValue(r.Context(), workspaceAgentParamContextKey{}, agent)
chi.RouteContext(ctx).URLParams.Add("workspace", build.WorkspaceID.String())
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Adding the workspace param here to check RBAC in the actual call.

next.ServeHTTP(rw, r.WithContext(ctx))
})
}
Expand Down
13 changes: 13 additions & 0 deletions coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/coder/coder/coderd/database"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/coderd/httpmw"
"github.com/coder/coder/coderd/rbac"
"github.com/coder/coder/coderd/turnconn"
"github.com/coder/coder/codersdk"
"github.com/coder/coder/peer"
Expand All @@ -31,6 +32,10 @@ import (

func (api *API) workspaceAgent(rw http.ResponseWriter, r *http.Request) {
workspaceAgent := httpmw.WorkspaceAgentParam(r)
workspace := httpmw.WorkspaceParam(r)
if !api.Authorize(rw, r, rbac.ActionRead, workspace) {
return
}
dbApps, err := api.Database.GetWorkspaceAppsByAgentID(r.Context(), workspaceAgent.ID)
if err != nil && !xerrors.Is(err, sql.ErrNoRows) {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Expand Down Expand Up @@ -58,6 +63,10 @@ func (api *API) workspaceAgentDial(rw http.ResponseWriter, r *http.Request) {
defer api.websocketWaitGroup.Done()

workspaceAgent := httpmw.WorkspaceAgentParam(r)
workspace := httpmw.WorkspaceParam(r)
if !api.Authorize(rw, r, rbac.ActionUpdate, workspace) {
return
}
apiAgent, err := convertWorkspaceAgent(workspaceAgent, nil, api.AgentConnectionUpdateFrequency)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Expand Down Expand Up @@ -369,6 +378,10 @@ func (api *API) workspaceAgentPTY(rw http.ResponseWriter, r *http.Request) {
defer api.websocketWaitGroup.Done()

workspaceAgent := httpmw.WorkspaceAgentParam(r)
workspace := httpmw.WorkspaceParam(r)
if !api.Authorize(rw, r, rbac.ActionUpdate, workspace) {
return
}
apiAgent, err := convertWorkspaceAgent(workspaceAgent, nil, api.AgentConnectionUpdateFrequency)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Expand Down
47 changes: 25 additions & 22 deletions site/src/components/Resources/Resources.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,10 @@ interface ResourcesProps {
resources?: WorkspaceResource[]
getResourcesError?: Error
workspace: Workspace
canUpdateWorkspace: boolean
}

export const Resources: FC<ResourcesProps> = ({ resources, getResourcesError, workspace }) => {
export const Resources: FC<ResourcesProps> = ({ resources, getResourcesError, workspace, canUpdateWorkspace }) => {
const styles = useStyles()
const theme: Theme = useTheme()

Expand All @@ -89,7 +90,7 @@ export const Resources: FC<ResourcesProps> = ({ resources, getResourcesError, wo
<AgentHelpTooltip />
</Stack>
</TableCell>
<TableCell>{Language.accessLabel}</TableCell>
{canUpdateWorkspace && <TableCell>{Language.accessLabel}</TableCell>}
<TableCell>{Language.statusLabel}</TableCell>
</TableHeaderRow>
</TableHead>
Expand Down Expand Up @@ -130,28 +131,30 @@ export const Resources: FC<ResourcesProps> = ({ resources, getResourcesError, wo
{agent.name}
<span className={styles.operatingSystem}>{agent.operating_system}</span>
</TableCell>
<TableCell>
<Stack>
{agent.status === "connected" && (
<TerminalLink
className={styles.accessLink}
workspaceName={workspace.name}
agentName={agent.name}
userName={workspace.owner_name}
/>
)}
{agent.status === "connected" &&
agent.apps.map((app) => (
<AppLink
key={app.name}
appIcon={app.icon}
appName={app.name}
userName={workspace.owner_name}
{canUpdateWorkspace && (
Copy link
Member

Choose a reason for hiding this comment

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

I could see this living in its own component given the length of the file.

<TableCell>
<Stack>
{agent.status === "connected" && (
<TerminalLink
className={styles.accessLink}
workspaceName={workspace.name}
agentName={agent.name}
userName={workspace.owner_name}
/>
))}
</Stack>
</TableCell>
)}
{agent.status === "connected" &&
agent.apps.map((app) => (
<AppLink
key={app.name}
appIcon={app.icon}
appName={app.name}
userName={workspace.owner_name}
workspaceName={workspace.name}
/>
))}
</Stack>
</TableCell>
)}
<TableCell>
<span style={{ color: getDisplayAgentStatus(theme, agent).color }}>
{getDisplayAgentStatus(theme, agent).status}
Expand Down
7 changes: 7 additions & 0 deletions site/src/components/Workspace/Workspace.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ Started.args = {
handleStop: action("stop"),
resources: [Mocks.MockWorkspaceResource, Mocks.MockWorkspaceResource2],
builds: [Mocks.MockWorkspaceBuild],
canUpdateWorkspace: true,
}

export const WithoutUpdateAccess = Template.bind({})
WithoutUpdateAccess.args = {
...Started.args,
canUpdateWorkspace: false,
}

export const Starting = Template.bind({})
Expand Down
9 changes: 8 additions & 1 deletion site/src/components/Workspace/Workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface WorkspaceProps {
resources?: TypesGen.WorkspaceResource[]
getResourcesError?: Error
builds?: TypesGen.WorkspaceBuild[]
canUpdateWorkspace: boolean
}

/**
Expand All @@ -44,6 +45,7 @@ export const Workspace: FC<WorkspaceProps> = ({
resources,
getResourcesError,
builds,
canUpdateWorkspace,
}) => {
const styles = useStyles()
const navigate = useNavigate()
Expand Down Expand Up @@ -80,7 +82,12 @@ export const Workspace: FC<WorkspaceProps> = ({
<WorkspaceStats workspace={workspace} />

{!!resources && !!resources.length && (
<Resources resources={resources} getResourcesError={getResourcesError} workspace={workspace} />
<Resources
resources={resources}
getResourcesError={getResourcesError}
workspace={workspace}
canUpdateWorkspace={canUpdateWorkspace}
/>
)}

<WorkspaceSection title="Timeline" contentsProps={{ className: styles.timelineContents }}>
Expand Down
20 changes: 16 additions & 4 deletions site/src/pages/WorkspacePage/WorkspacePage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMachine } from "@xstate/react"
import React, { useEffect } from "react"
import { useMachine, useSelector } from "@xstate/react"
import React, { useContext, useEffect } from "react"
import { Helmet } from "react-helmet"
import { useParams } from "react-router-dom"
import { DeleteWorkspaceDialog } from "../../components/DeleteWorkspaceDialog/DeleteWorkspaceDialog"
Expand All @@ -8,6 +8,8 @@ import { FullScreenLoader } from "../../components/Loader/FullScreenLoader"
import { Workspace } from "../../components/Workspace/Workspace"
import { firstOrItem } from "../../util/array"
import { pageTitle } from "../../util/page"
import { selectUser } from "../../xServices/auth/authSelectors"
import { XServiceContext } from "../../xServices/StateContext"
import { workspaceMachine } from "../../xServices/workspace/workspaceXService"
import { workspaceScheduleBannerMachine } from "../../xServices/workspaceSchedule/workspaceScheduleBannerXService"

Expand All @@ -16,8 +18,17 @@ export const WorkspacePage: React.FC = () => {
const username = firstOrItem(usernameQueryParam, null)
const workspaceName = firstOrItem(workspaceQueryParam, null)

const [workspaceState, workspaceSend] = useMachine(workspaceMachine)
const { workspace, resources, getWorkspaceError, getResourcesError, builds } = workspaceState.context
const xServices = useContext(XServiceContext)
const me = useSelector(xServices.authXService, selectUser)

const [workspaceState, workspaceSend] = useMachine(workspaceMachine, {
context: {
userId: me?.id,
},
})
const { workspace, resources, getWorkspaceError, getResourcesError, builds, permissions } = workspaceState.context

const canUpdateWorkspace = !!permissions?.updateWorkspace

const [bannerState, bannerSend] = useMachine(workspaceScheduleBannerMachine)

Expand Down Expand Up @@ -56,6 +67,7 @@ export const WorkspacePage: React.FC = () => {
resources={resources}
getResourcesError={getResourcesError instanceof Error ? getResourcesError : undefined}
builds={builds}
canUpdateWorkspace={canUpdateWorkspace}
/>
<DeleteWorkspaceDialog
isOpen={workspaceState.matches({ ready: { build: "askingDelete" } })}
Expand Down
4 changes: 4 additions & 0 deletions site/src/xServices/auth/authSelectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ export const selectOrgId = (state: AuthState): string | undefined => {
export const selectPermissions = (state: AuthState): AuthContext["permissions"] => {
return state.context.permissions
}

export const selectUser = (state: AuthState): AuthContext["me"] => {
return state.context.me
}
Loading