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(swagger): handle redirects from OIDC IdP and initialize swagger #467

Merged
merged 4 commits into from
Mar 22, 2024
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"@kong-ui-public/analytics-utilities": "0.10.1",
"@kong-ui-public/copy-uuid": "1.1.5",
"@kong-ui-public/document-viewer": "2.0.16",
"@kong-ui-public/spec-renderer": "2.1.0",
"@kong-ui-public/spec-renderer": "2.1.5",
"@kong/kong-auth-elements": "2.11.1",
"@kong/kongponents": "8.127.0",
"@kong/sdk-portal-js": "2.10.0",
Expand Down
92 changes: 92 additions & 0 deletions src/views/Spec.vue
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@

<SpecDetails
v-else-if="spec"
ref="specDetailsRef"
class="w-100"
:document="spec"
:has-sidebar="false"
Expand Down Expand Up @@ -235,6 +236,19 @@ export default defineComponent({
const $route = useRoute()
const { portalApiV2 } = usePortalApi()

const specDetailsRef = ref(null)

watch(() => specDetailsRef.value, (newValue, oldValue) => {
if (newValue && newValue !== oldValue) {
newValue.swaggerInstance.instance.initOAuth({
usePkceWithAuthorizationCodeGrant: true,
additionalQueryStringParams: {
nonce: Math.random().toString(36).substring(7)
}
})
}
})

// fallback in case the operations are loaded in after the spec.
watch(() => sidebarOperations.value, async () => {
if (sidebarOperations.value?.length) {
Expand Down Expand Up @@ -288,12 +302,85 @@ export default defineComponent({
}
})

const processOauth2Redirect = async () => {
const oauth2 = window.opener?.swaggerUIRedirectOauth2
const sentState = oauth2.state
const redirectUrl = oauth2.redirectUrl
let qp
Copy link
Member

Choose a reason for hiding this comment

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

Is it possible to use this.$route.query to get the params?


if (/code|token|error/.test($route.hash)) {
qp = $route.hash.substring(1).replace('?', '&')
} else {
qp = location.search.substring(1)
}

const arr = qp.split('&')

arr.forEach(function (v, i, _arr) { _arr[i] = '"' + v.replace('=', '":"') + '"' })
qp = qp
? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === '' ? value : decodeURIComponent(value)
}
)
: {}
Copy link
Contributor

Choose a reason for hiding this comment

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

This algorithm won't be able to handle params that don't have a value (e.g., query params strings like a=z&x).

I think it would be better to have an algorithm like

Suggested change
const arr = qp.split('&')
arr.forEach(function (v, i, _arr) { _arr[i] = '"' + v.replace('=', '":"') + '"' })
qp = qp
? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === '' ? value : decodeURIComponent(value)
}
)
: {}
qp = Object.fromEntries(qp.split('&').map(param => param.split('=')))

or if possible use another way of accessing query params on the route as Nate commented.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah makes sense, this was a direct lift from the helper functions in swagger-ui. I'll port it over to be more vue-friendly and hopefully catch more edge cases.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

How does this look, @Mierenga ? I think this should pretty safely account for both cases as well as empty

// called with $route.hash or $route.query
const parseRouteData = (routeData: string | LocationQuery): Record<string, string> => {
  if (!routeData) return {};

  // handle locationQuery
  if (typeof routeData === 'object') {
    // decode any URI components:
    const routeDataDecoded = Object.keys(routeData).reduce((acc, key) => {
      acc[key] = decodeURIComponent(routeData[key].toString())
      return acc
    }, {})
    return routeDataDecoded
  }

  const data = routeData.startsWith('#') ? routeData.substring(1) : routeData;
  const pairs = data.split('&');
  const result = {};

  pairs.forEach(pair => {
    const [key, value] = pair.split('=');
    result[key] = decodeURIComponent(value);
  });

  return result;
};

Meaning that:

window.open('http://localhost:5173/spec/8c655d31-0c89-4660-96d0-829dd92f9e98/oauth2-redirect.html?a=z&x')

const routeHashData = parseRouteData($route.hash);
const routeQueryData = parseRouteData($route.query);
const routeData = { ...routeHashData, ...routeQueryData };

// routeData becomes `{a:'z',x:''}`


const isValid = qp.state === sentState

if ((
oauth2.auth.schema.get('flow') === 'accessCode' ||
oauth2.auth.schema.get('flow') === 'authorizationCode' ||
oauth2.auth.schema.get('flow') === 'authorization_code'
) && !oauth2.auth.code) {
if (!isValid) {
oauth2.errCb({
authId: oauth2.auth.name,
source: 'auth',
level: 'warning',
message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
})
}

if (qp.code) {
delete oauth2.state
oauth2.auth.code = qp.code
oauth2.callback({ auth: oauth2.auth, redirectUrl })
} else {
let oauthErrorMsg
if (qp.error) {
oauthErrorMsg = '[' + qp.error + ']: ' +
(qp.error_description ? qp.error_description + '. ' : 'no accessCode received from the server. ') +
(qp.error_uri ? 'More info: ' + qp.error_uri : '')
}

oauth2.errCb({
authId: oauth2.auth.name,
source: 'auth',
level: 'error',
message: oauthErrorMsg || '[Authorization failed]: no accessCode received from the server'
})
}
} else {
oauth2.callback({ auth: oauth2.auth, token: qp, isValid, redirectUrl })
}

window.close()
}

onMounted(async () => {
isAllowedToRegister.value = await canUserAccess({
action: 'register',
productId: $route.params.product.toString()
})

try {
if ($route.path.includes('oauth2-redirect.html')) {
await processOauth2Redirect()
}
} catch (error) {
console.error(error)
}

await processProduct()
await loadSwagger()

Expand Down Expand Up @@ -541,6 +628,7 @@ export default defineComponent({
}

return {
specDetailsRef,
authMethodLabelObj,
helpText,
viewSpecModalIsVisible,
Expand Down Expand Up @@ -643,5 +731,9 @@ export default defineComponent({
border: 1px solid transparent;
color: var(--button_colors-primary-text, #fff);
}

.swagger-ui .auth-container .errors {
word-wrap: break-word;
}
}
</style>
67 changes: 46 additions & 21 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1143,10 +1143,10 @@
flat "^6.0.1"
intl-messageformat "^10.5.8"

"@kong-ui-public/i18n@^2.1.3":
version "2.1.3"
resolved "https://registry.yarnpkg.com/@kong-ui-public/i18n/-/i18n-2.1.3.tgz#69274abb275c612f999f6e0944da11c341fdc347"
integrity sha512-KPEzrVsfTjAGTZ2kcPK+b+hRwDlLjeY4Ys6VnTn+qYEYJjiPEjKansw5zJk33c8R4CTM4a7Zf5DPg1zaWjmNoQ==
"@kong-ui-public/i18n@^2.1.4":
version "2.1.4"
resolved "https://registry.yarnpkg.com/@kong-ui-public/i18n/-/i18n-2.1.4.tgz#14358c953511da14ca59c0475a7c6f8706abf1e7"
integrity sha512-fueflh8p98qLITjfqzRoIDXhqTWv5GEiFduSxs5p2f5J1bIeczRTwG3T3k86KI8HwbiU3jG2r5+rZ6d/WFPHYg==
dependencies:
"@formatjs/intl" "^2.10.0"
flat "^6.0.1"
Expand All @@ -1160,27 +1160,27 @@
"@kong/icons" "^1.8.0"
approximate-number "^2.1.1"

"@kong-ui-public/[email protected].0":
version "2.1.0"
resolved "https://registry.yarnpkg.com/@kong-ui-public/spec-renderer/-/spec-renderer-2.1.0.tgz#004d438c7cbfcf5b3904ad081703d32cf71ada87"
integrity sha512-b7LaYLVOoWRyirpm+52Da6IgrFE+MA2A5JgyssrZXBARGClJczCeR3t5G18ATMshKXdR4lAetMCKzk7Scy+LDQ==
"@kong-ui-public/[email protected].5":
version "2.1.5"
resolved "https://registry.yarnpkg.com/@kong-ui-public/spec-renderer/-/spec-renderer-2.1.5.tgz#d91000e323b5f0a07f07e998583f71cc368f5b5c"
integrity sha512-RETh6TGgSOtRViZZOO+XYFO+Hu/eUohrsQmScYTuZvroW/sLqmQNkbZMN5LNUb62D2xgCQyaDiUgUgYN2jpLsg==
dependencies:
"@kong-ui-public/i18n" "^2.1.3"
"@kong-ui-public/swagger-ui-web-component" "^0.11.0"
"@kong-ui-public/i18n" "^2.1.4"
"@kong-ui-public/swagger-ui-web-component" "^0.11.3"
"@kong/icons" "^1.8.14"
lodash.clonedeep "^4.5.0"
uuid "^9.0.1"

"@kong-ui-public/swagger-ui-web-component@^0.11.0":
version "0.11.0"
resolved "https://registry.yarnpkg.com/@kong-ui-public/swagger-ui-web-component/-/swagger-ui-web-component-0.11.0.tgz#9b4b938e6e0ecd3adcc35f364eab569d02930ab4"
integrity sha512-KkbK+XFbFNhGNqufJlNnJ3TBsAb3Egf7HY9eDdV4f7/6VobfRSwgiHmsFTl2PmeIiLI2BulO7lfzi5MF3LJFAg==
"@kong-ui-public/swagger-ui-web-component@^0.11.3":
version "0.11.3"
resolved "https://registry.yarnpkg.com/@kong-ui-public/swagger-ui-web-component/-/swagger-ui-web-component-0.11.3.tgz#7631f0b7642529759157fd406150344c2ede367c"
integrity sha512-Ku7rH6Z897VR8TxWxDh9OBjfAf+nsk9tYgmS7obNp82vuS21/m/iVAls1MQxhjQNMFADYKurmgSKj3tgfMsj6g==
dependencies:
"@kong/swagger-ui-kong-theme-universal" "^4.3.3"
react "17.0.2"
react-dom "17.0.2"
swagger-client "^3.25.4"
swagger-ui "^5.1.0"
swagger-client "^3.26.0"
swagger-ui "^5.1.3"

"@kong/icons@^1.8.0":
version "1.8.0"
Expand Down Expand Up @@ -10285,7 +10285,16 @@ stream@^0.0.2:
dependencies:
emitter-component "^1.1.1"

"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
"string-width-cjs@npm:string-width@^4.2.0":
version "4.2.3"
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
dependencies:
emoji-regex "^8.0.0"
is-fullwidth-code-point "^3.0.0"
strip-ansi "^6.0.1"

"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3:
version "4.2.3"
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
Expand Down Expand Up @@ -10353,7 +10362,7 @@ stringify-object@^3.2.1, stringify-object@^3.3.0:
is-obj "^1.0.1"
is-regexp "^1.0.0"

"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1:
"strip-ansi-cjs@npm:strip-ansi@^6.0.1":
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
Expand All @@ -10367,6 +10376,13 @@ strip-ansi@^3.0.0:
dependencies:
ansi-regex "^2.0.0"

strip-ansi@^6.0.0, strip-ansi@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
dependencies:
ansi-regex "^5.0.1"

strip-ansi@^7.0.1:
version "7.1.0"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45"
Expand Down Expand Up @@ -10492,7 +10508,7 @@ svgo@^3.0.2:
csso "^5.0.5"
picocolors "^1.0.0"

swagger-client@^3.25.4, swagger-client@^3.26.0:
swagger-client@^3.26.0:
version "3.26.0"
resolved "https://registry.yarnpkg.com/swagger-client/-/swagger-client-3.26.0.tgz#95d28f0c61f39717b84e0e3914319d817c59a868"
integrity sha512-1yFR/S2V3v5DwgmNePoHEjq2dZJxDx1leDQ53r5M4hZs+dozm9VnznlSl9a1V5iTYw4UsS4PQuBRQsmBH21ViA==
Expand All @@ -10513,7 +10529,7 @@ swagger-client@^3.25.4, swagger-client@^3.26.0:
qs "^6.10.2"
traverse "~0.6.6"

swagger-ui@^5.1.0:
swagger-ui@^5.1.3:
version "5.12.0"
resolved "https://registry.yarnpkg.com/swagger-ui/-/swagger-ui-5.12.0.tgz#e10fc5d626670a75e596e23a65ec84c374cbe4ce"
integrity sha512-Zf62HaUpUc0H1VMcB+HMp1ARaof+xv7ppU4XXbDHSsKxLxxOfQrRxsmoBdaJz2jfgHAes3h7FMsAy6vpCDWv9Q==
Expand Down Expand Up @@ -11439,7 +11455,7 @@ wordwrap@^1.0.0:
resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb"
integrity sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==

"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0:
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0":
version "7.0.0"
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
Expand All @@ -11457,6 +11473,15 @@ wrap-ansi@^6.2.0:
string-width "^4.1.0"
strip-ansi "^6.0.0"

wrap-ansi@^7.0.0:
version "7.0.0"
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
dependencies:
ansi-styles "^4.0.0"
string-width "^4.1.0"
strip-ansi "^6.0.0"

wrap-ansi@^8.1.0:
version "8.1.0"
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214"
Expand Down
Loading