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

feat: check if user is fn author w/ exec engine #2310

Merged
merged 1 commit into from
May 31, 2024
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
17 changes: 3 additions & 14 deletions packages/frontend-2/components/automate/function/CreateDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ import type {
CreatableFunctionTemplate,
FunctionDetailsFormValues
} from '~/lib/automate/helpers/functions'
import { automateGithubAppAuthorizationCallback } from '~/lib/common/helpers/route'
import { useEnumSteps, useEnumStepsWidgetSetup } from '~/lib/form/composables/steps'
import { useForm } from 'vee-validate'
import { useCreateAutomateFunction } from '~/lib/automate/composables/management'
Expand Down Expand Up @@ -128,13 +127,9 @@ const stepsWidgetData = computed(() => [
])

const selectedTemplate = ref<CreatableFunctionTemplate>()
const githubScopes = ref(['read:org', 'read:user', 'repo'])
const createdFunction =
ref<AutomateFunctionCreateDialogDoneStep_AutomateFunctionFragment>()

const {
public: { automateGhClientId }
} = useRuntimeConfig()
const apiBaseUrl = useApiOrigin()
const { enumStep, step } = useEnumSteps({ order: stepsOrder })
const {
Expand All @@ -157,14 +152,8 @@ const title = computed(() => {
})

const authorizeGithubUrl = computed(() => {
const redirectUrl = new URL(automateGithubAppAuthorizationCallback, apiBaseUrl)
const url = new URL(`/login/oauth/authorize`, 'https://github.com')

url.searchParams.set('client_id', automateGhClientId)
url.searchParams.set('scope', githubScopes.value.join(','))
url.searchParams.set('redirect_uri', redirectUrl.toString())

return url.toString()
// TODO:
fabis94 marked this conversation as resolved.
Show resolved Hide resolved
return new URL('/', apiBaseUrl).toString()
})

const buttons = computed((): LayoutDialogButton[] => {
Expand All @@ -185,7 +174,7 @@ const buttons = computed((): LayoutDialogButton[] => {
text: 'Authorize',
props: {
fullWidth: true,
disabled: !automateGhClientId.length,
disabled: true,
to: authorizeGithubUrl.value,
external: true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
v-on="on"
/>
<FormButton
v-if="canCreateFunction && false"
v-if="canCreateFunction"
:icon-left="PlusIcon"
@click="() => (createDialogOpen = true)"
>
Expand Down Expand Up @@ -68,10 +68,8 @@ const props = defineProps<{
activeUser: Optional<AutomateFunctionsPageHeader_QueryFragment['activeUser']>
serverInfo: Optional<AutomateFunctionsPageHeader_QueryFragment['serverInfo']>
}>()
const {
public: { automateGhClientId }
} = useRuntimeConfig()
const search = defineModel<string>('search')

const { on, bind } = useDebouncedTextInput({ model: search })
const { triggerNotification } = useGlobalToast()
const route = useRoute()
Expand All @@ -83,10 +81,7 @@ const availableTemplates = computed(
() => props.serverInfo?.automate.availableFunctionTemplates || []
)
const canCreateFunction = computed(
() =>
!!props.activeUser?.id &&
!!automateGhClientId.length &&
!!availableTemplates.value.length
() => !!props.activeUser?.id && !!availableTemplates.value.length
)

if (process.client) {
Expand Down
11 changes: 11 additions & 0 deletions packages/frontend-2/middleware/requiresAutomateEnabled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default defineNuxtRouteMiddleware(() => {
const isAutomateEnabled = useIsAutomateModuleEnabled()
if (!isAutomateEnabled.value) {
return abortNavigation(
createError({
statusCode: 404,
message: 'Page not found'
})
)
}
})
14 changes: 1 addition & 13 deletions packages/frontend-2/pages/functions/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,7 @@ import { graphql } from '~/lib/common/generated/gql'
// TODO: Proper search & pagination

definePageMeta({
middleware: [
function () {
const isAutomateEnabled = useIsAutomateModuleEnabled()
if (!isAutomateEnabled.value) {
return abortNavigation(
createError({
statusCode: 404,
message: 'Page not found'
})
)
}
}
]
middleware: ['requires-automate-enabled']
})

const pageQuery = graphql(`
Expand Down
30 changes: 27 additions & 3 deletions packages/server/modules/automate/clients/executionEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
isVersionCreatedTriggerManifest
} from '@/modules/automate/helpers/types'
import { MisconfiguredEnvironmentError } from '@/modules/shared/errors'
import { speckleAutomateUrl } from '@/modules/shared/helpers/envHelper'
import { getServerOrigin, speckleAutomateUrl } from '@/modules/shared/helpers/envHelper'
import {
Nullable,
SourceAppName,
Expand Down Expand Up @@ -128,10 +128,10 @@ const invokeRequest = async (params: {
}

export const createAutomation = async (params: {
speckleServerUrl: string
speckleServerUrl?: string
authCode: string
}) => {
const { speckleServerUrl, authCode } = params
const { speckleServerUrl = getServerOrigin(), authCode } = params

const url = getApiUrl(`/api/v2/automations`)

Expand Down Expand Up @@ -383,6 +383,30 @@ export const getFunctions = async (params: {
return result
}

type UserGithubAuthStateResponse = {
userHasAuthorizedGithubApp: boolean
}

export const getUserGithubAuthState = async (params: {
speckleServerUrl?: string
userId: string
}) => {
const { speckleServerUrl = getServerOrigin(), userId: speckleUserId } = params
const speckleServerOrigin = new URL(speckleServerUrl).origin

const url = getApiUrl(`/api/v2/functions/auth/githubapp`, {
query: {
speckleServerOrigin,
speckleUserId
}
})

return await invokeJsonRequest<UserGithubAuthStateResponse>({
url,
method: 'get'
})
}

export async function* getAutomationRunLogs(params: {
automationId: string
automationRunId: string
Expand Down
49 changes: 39 additions & 10 deletions packages/server/modules/automate/graph/resolvers/automate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import {
getFunction,
getFunctionRelease,
getFunctions,
getFunctionReleases
getFunctionReleases,
getUserGithubAuthState
} from '@/modules/automate/clients/executionEngine'
import {
GetProjectAutomationsParams,
Expand Down Expand Up @@ -66,7 +67,10 @@ import {
reportFunctionRunStatus,
ReportFunctionRunStatusDeps
} from '@/modules/automate/services/runsManagement'
import { FunctionNotFoundError } from '@/modules/automate/errors/management'
import {
AutomationNotFoundError,
FunctionNotFoundError
} from '@/modules/automate/errors/management'
import {
FunctionReleaseSchemaType,
dbToGraphqlTriggerTypeMap,
Expand Down Expand Up @@ -97,7 +101,6 @@ import {
ExecutionEngineFailedResponseError,
ExecutionEngineNetworkError
} from '@/modules/automate/errors/executionEngine'
import { automateLogger } from '@/logging/logging'

/**
* TODO:
Expand Down Expand Up @@ -163,7 +166,16 @@ export = (FF_AUTOMATE_MODULE_ENABLED
},
Project: {
async automation(parent, args, ctx) {
return ctx.loaders.streams.getAutomation.forStream(parent.id).load(args.id)
const res = ctx.loaders.streams.getAutomation
.forStream(parent.id)
.load(args.id)
if (!res) {
if (!res) {
throw new AutomationNotFoundError()
}
}

return res
},
async automations(parent, args) {
const retrievalArgs: GetProjectAutomationsParams = {
Expand Down Expand Up @@ -287,7 +299,7 @@ export = (FF_AUTOMATE_MODULE_ENABLED
parent.functionId
)
if (!fn) {
automateLogger.warn(
ctx.log.warn(
{ id: parent.functionId, fnRunId: parent.id, runid: parent.runId },
'AutomateFunctionRun function unexpectedly not found'
)
Expand Down Expand Up @@ -557,11 +569,28 @@ export = (FF_AUTOMATE_MODULE_ENABLED
}
},
User: {
// TODO: Needs proper integration w/ Execution engine
automateInfo: () => ({
hasAutomateGithubApp: false,
availableGithubOrgs: []
})
automateInfo: async (parent, _args, ctx) => {
const userId = parent.id

let hasAutomateGithubApp = false
try {
const authState = await getUserGithubAuthState({ userId })
hasAutomateGithubApp = authState.userHasAuthorizedGithubApp
} catch (e) {
if (e instanceof ExecutionEngineFailedResponseError) {
if (e.response.statusMessage === 'FunctionCreatorDoesNotExist') {
hasAutomateGithubApp = false
}
} else {
ctx.log.error(e, 'Failed to resolve user automate github auth state')
}
}

return {
hasAutomateGithubApp,
availableGithubOrgs: []
}
}
},
ServerInfo: {
// TODO: Needs proper integration w/ Execution engine
Expand Down