diff --git a/.changeset/green-otters-grin.md b/.changeset/green-otters-grin.md new file mode 100644 index 0000000000..abfd332a2b --- /dev/null +++ b/.changeset/green-otters-grin.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': patch +--- + +Add support for configure an LDAP query filter on multiple lines. diff --git a/.changeset/metal-foxes-speak.md b/.changeset/metal-foxes-speak.md new file mode 100644 index 0000000000..45b8ae3c7c --- /dev/null +++ b/.changeset/metal-foxes-speak.md @@ -0,0 +1,5 @@ +--- +'@backstage/catalog-model': patch +--- + +Add getEntitySourceLocation helper diff --git a/.changeset/old-clouds-whisper.md b/.changeset/old-clouds-whisper.md new file mode 100644 index 0000000000..edaba13ad7 --- /dev/null +++ b/.changeset/old-clouds-whisper.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-kubernetes-backend': patch +--- + +Use `string` TypeScript type instead of `String`. diff --git a/.changeset/rare-mayflies-remain.md b/.changeset/rare-mayflies-remain.md new file mode 100644 index 0000000000..bb85afd344 --- /dev/null +++ b/.changeset/rare-mayflies-remain.md @@ -0,0 +1,5 @@ +--- +'@backstage/core': patch +--- + +Pass `inverse` prop to Gauge from GaugeCard diff --git a/.changeset/sour-dryers-sort.md b/.changeset/sour-dryers-sort.md new file mode 100644 index 0000000000..ee15655e82 --- /dev/null +++ b/.changeset/sour-dryers-sort.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-api-docs': patch +--- + +chore(deps): bump @asyncapi/react-component from 0.19.2 to 0.22.3 diff --git a/.changeset/techdocs-chatty-impalas-compare.md b/.changeset/techdocs-chatty-impalas-compare.md new file mode 100644 index 0000000000..26e7fd571d --- /dev/null +++ b/.changeset/techdocs-chatty-impalas-compare.md @@ -0,0 +1,6 @@ +--- +'@backstage/plugin-techdocs': patch +--- + +Reworked the TechDocs plugin to support using the configured company name instead of +'Backstage' in the page title. diff --git a/.changeset/techdocs-dry-starfishes-carry.md b/.changeset/techdocs-dry-starfishes-carry.md new file mode 100644 index 0000000000..f5841c6994 --- /dev/null +++ b/.changeset/techdocs-dry-starfishes-carry.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-techdocs': patch +--- + +Add borders to TechDocs tables and increase font size. Fixes #5264 and #5276. diff --git a/.changeset/thick-frogs-hang.md b/.changeset/thick-frogs-hang.md new file mode 100644 index 0000000000..44add55206 --- /dev/null +++ b/.changeset/thick-frogs-hang.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-scaffolder-backend': patch +--- + +Fix execution of the GitHub Pull Request publish action on Windows. diff --git a/.changeset/tiny-games-hide.md b/.changeset/tiny-games-hide.md new file mode 100644 index 0000000000..2687174060 --- /dev/null +++ b/.changeset/tiny-games-hide.md @@ -0,0 +1,5 @@ +--- +'@backstage/catalog-client': patch +--- + +Make sure the `CatalogClient` escapes URL parameters correctly. diff --git a/.changeset/witty-hotels-know.md b/.changeset/witty-hotels-know.md new file mode 100644 index 0000000000..4b20111fa7 --- /dev/null +++ b/.changeset/witty-hotels-know.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-tech-radar': patch +--- + +Add markdown support for tech radar entry description diff --git a/.changeset/young-kids-remember.md b/.changeset/young-kids-remember.md new file mode 100644 index 0000000000..c07097234f --- /dev/null +++ b/.changeset/young-kids-remember.md @@ -0,0 +1,5 @@ +--- +'@backstage/cli': patch +--- + +Disable hot reloading in CI environments. diff --git a/.github/styles/vocab.txt b/.github/styles/vocab.txt index 8c385e1bbb..226af9bf0a 100644 --- a/.github/styles/vocab.txt +++ b/.github/styles/vocab.txt @@ -114,6 +114,7 @@ dataflow deadnaming debounce declaratively +deps destructured dev devops diff --git a/contrib/docs/tutorials/aws-alb-aad-oidc-auth.md b/contrib/docs/tutorials/aws-alb-aad-oidc-auth.md new file mode 100644 index 0000000000..ba0aef89ea --- /dev/null +++ b/contrib/docs/tutorials/aws-alb-aad-oidc-auth.md @@ -0,0 +1,170 @@ +# Using AWS Application Load Balancer with Azure Active Directory to authenticate requests + +Backstage allows offloading the responsibility of authenticating users to an AWS Application Load Balancer (**ALB**), leveraging the authentication support on ALB. +This tutorial shows how to use authentication on an ALB sitting in front of Backstage. +Azure Active Directory (**AAD**) is used as identity provider but any identity provider supporting OpenID Connect (OIDC) can be used. + +It is assumed an ALB is already serving traffic in front of a Backstage instance configured to serve the frontend app from the backend. + +## Infrastructure setup + +### AAD App + +The AAD App is used to execute the authentication flow, serve and refresh the identity token. + +Create the AAD App following the steps outlined in `Create a Microsoft App Registration in Microsoft Portal` section from the tutorial [Monorepo App Setup With Authentication][monorepo-app-setup-with-auth]. + +Instead of `localhost` addresses, use the following values. + +- Identifier URI: `https://backstage.yourdomain.com` +- Redirect URI: `https://backstage.yourdomain.com/oauth2/idpresponse` + +`Application (client) Id`, `Directory (tenant) ID` and `client secret`values will be used while configuring the ALB. + +### ALB + +In the AWS console, configure ALB Authentication: + +- Edit the ALB rule used to forward the traffic to Backstage and add a new `Authenticate` action. The action will have higher priority compared to the existing `Forward to`. +- Select `OIDC` under `Authenticate` +- Set `Issuer` to `https://login.microsoftonline.com/{TENANT_ID}/v2.0`, replacing `{TENANT_ID}` with the value of `Directory (tenant) ID` of the AAD App. +- Set `Authorization endpoint` to `https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize`, replacing `{TENANT_ID}` with the value of `Directory (tenant) ID` of the AAD App. +- Set `Token endpoint` to `https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize`, replacing `{TENANT_ID}` with the value of `Directory (tenant) ID` of the AAD App. +- Set `User info endpoint` to `https://graph.microsoft.com/oidc/userinfo` +- Set `Client ID` to the AAD App `Application (client) Id` +- Set `Client secret` to the AAD APP `client secret` + +Use the following advanced settings: + +- `Session cookie name` = `AWSELBAuthSessionCookie` +- `Session timeout` = `604800` seconds +- `Scope` = `openid profile offline_access` +- `Action on unauthenticated request` = `Autenticate (client reattempt)` + +Once you've saved the action, you should see an authentication flow be triggered against AAD when visiting Backstage address at `https://backstage.yourdomain.com`. The flow will not complete successfully as the Backstage app isn't yet configured properly. + +## Backstage changes + +### Frontend + +The Backstage App needs a SignInPage when authentication is required. +When using ALB authentication Backstage will only be loaded once the user has successfully authenticated; we won't need to display a SignIn page, however we will need to create a dummy SignIn component that can refresh the token. + +- edit `packages/app/src/App.tsx` +- import the following two additional definitions from `@backstage/core`: `useApi`, `configApiRef`; these will be used to check whether Backstage is running locally or behind an ALB +- add the following definition just before the app is created (`const app = createApp`): + +```ts +const DummySignInComponent: any = (props: any) => { + try { + const config = useApi(configApiRef); + const shouldAuth = !!config.getOptionalConfig('auth.providers.awsalb'); + if (shouldAuth) { + fetch(`${window.location.origin}/api/auth/awsalb/refresh`) + .then(data => data.json()) + .then(data => { + props.onResult({ + userId: data.backstageIdentity.id, + profile: data.profile, + }); + }); + } else { + props.onResult({ + userId: 'guest', + profile: { + email: 'guest@example.com', + displayName: 'Guest', + picture: '', + }, + }); + } + return
; + } catch (err) { + return
{err.message}
; + } +}; +``` + +- add `DummySignInComponent` as `SignInPage`: + +```ts +const app = createApp({ + ... + components: { + SignInPage: DummySignInComponent, + ... + }, + ... +}); +``` + +### Backend + +When using ALB auth it is not possible to leverage the built-in auth config discovery mechanism implemented in the app created by default; bespoke logic needs to be implemented. + +- replace the content of `packages/backend/plugin/auth.ts` with the below + +```ts +import { + createRouter, + AuthResponse, + AuthProviderFactoryOptions, + defaultAuthProviderFactories, +} from '@backstage/plugin-auth-backend'; +import { PluginEnvironment } from '../types'; + +export default async function createPlugin({ + logger, + database, + config, + discovery, +}: PluginEnvironment) { + const identityResolver = (payload: any): Promise> => { + return Promise.resolve({ + providerInfo: {}, + profile: { + email: payload.email, + displayName: payload.name, + picture: payload.picture, + }, + backstageIdentity: { + id: payload.email, + }, + }); + }; + const providerFactories = { + awsalb: (options: AuthProviderFactoryOptions) => + defaultAuthProviderFactories.awsalb({ ...options, identityResolver }), + }; + return await createRouter({ + logger, + config, + database, + discovery, + providerFactories, + }); +} +``` + +### Configuration + +Use the following `auth` configuration when running Backstage on AWS: + +```yaml +auth: + providers: + awsalb: + issuer: + issuer: https://login.microsoftonline.com/{TENANT_ID}/v2.0 + region: { AWS_REGION } +``` + +Replace `{TENANT_ID}` with the value of `Directory (tenant) ID` of the AAD App and `{AWS_REGION}` with the AWS region identifier where the ALB is deployed (for example: `eu-central-1`). + +## Conclusion + +Once it's deployed, after going through the AAD authentication flow, Backstage should display the AAD user details. + + + +[monorepo-app-setup-with-auth-ms]: https://backstage.io/docs/tutorials/quickstart-app-auth#the-auth-configuration diff --git a/docs/features/software-catalog/well-known-annotations.md b/docs/features/software-catalog/well-known-annotations.md index 8ec4813799..0053c14b79 100644 --- a/docs/features/software-catalog/well-known-annotations.md +++ b/docs/features/software-catalog/well-known-annotations.md @@ -92,12 +92,14 @@ view and edit links need changing. # Example: metadata: annotations: - backstage.io/source-location: github:https://github.com/my-org/my-service + backstage.io/source-location: url:https://github.com/my-org/my-service/ ``` A `Location` reference that points to the source code of the entity (typically a `Component`). Useful when catalog files do not get ingested from the source code -repository itself. +repository itself. If the URL points to a folder, it is important that it is +suffixed with a `'/'` in order for relative path resolution to work +consistently. ### jenkins.io/github-folder diff --git a/microsite/pages/en/index.js b/microsite/pages/en/index.js index 47f9568d9b..a761d6b6e2 100644 --- a/microsite/pages/en/index.js +++ b/microsite/pages/en/index.js @@ -292,7 +292,7 @@ class Index extends React.Component { Build your own software templates Contribute diff --git a/packages/app/package.json b/packages/app/package.json index 2bac2e6e09..1fc0335aa2 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -42,10 +42,10 @@ "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@octokit/rest": "^18.0.12", - "@roadiehq/backstage-plugin-buildkite": "^0.3.0", - "@roadiehq/backstage-plugin-github-insights": "^0.3.3", - "@roadiehq/backstage-plugin-github-pull-requests": "^0.7.9", - "@roadiehq/backstage-plugin-travis-ci": "^0.4.7", + "@roadiehq/backstage-plugin-buildkite": "^1.0.0", + "@roadiehq/backstage-plugin-github-insights": "^1.0.0", + "@roadiehq/backstage-plugin-github-pull-requests": "^1.0.0", + "@roadiehq/backstage-plugin-travis-ci": "^1.0.0", "history": "^5.0.0", "prop-types": "^15.7.2", "react": "^16.12.0", diff --git a/packages/app/src/components/catalog/EntityPage.tsx b/packages/app/src/components/catalog/EntityPage.tsx index d8ee62a12c..d6f91957a9 100644 --- a/packages/app/src/components/catalog/EntityPage.tsx +++ b/packages/app/src/components/catalog/EntityPage.tsx @@ -81,27 +81,27 @@ import { EntitySentryContent } from '@backstage/plugin-sentry'; import { EntityTechdocsContent } from '@backstage/plugin-techdocs'; import { EntityTodoContent } from '@backstage/plugin-todo'; import { Button, Grid } from '@material-ui/core'; -// import { -// EntityBuildkiteContent, -// isBuildkiteAvailable, -// } from '@roadiehq/backstage-plugin-buildkite'; -// import { -// EntityGitHubInsightsContent, -// EntityLanguagesCard, -// EntityReadMeCard, -// EntityReleasesCard, -// isGithubInsightsAvailable, -// } from '@roadiehq/backstage-plugin-github-insights'; -// import { -// EntityGithubPullRequestsContent, -// EntityGithubPullRequestsOverviewCard, -// isGithubPullRequestsAvailable, -// } from '@roadiehq/backstage-plugin-github-pull-requests'; -// import { -// EntityTravisCIContent, -// EntityTravisCIOverviewCard, -// isTravisciAvailable, -// } from '@roadiehq/backstage-plugin-travis-ci'; +import { + EntityBuildkiteContent, + isBuildkiteAvailable, +} from '@roadiehq/backstage-plugin-buildkite'; +import { + EntityGithubInsightsContent, + EntityGithubInsightsLanguagesCard, + EntityGithubInsightsReadmeCard, + EntityGithubInsightsReleasesCard, + isGithubInsightsAvailable, +} from '@roadiehq/backstage-plugin-github-insights'; +import { + EntityGithubPullRequestsContent, + EntityGithubPullRequestsOverviewCard, + isGithubPullRequestsAvailable, +} from '@roadiehq/backstage-plugin-github-pull-requests'; +import { + EntityTravisCIContent, + EntityTravisCIOverviewCard, + isTravisciAvailable, +} from '@roadiehq/backstage-plugin-travis-ci'; const EntityLayoutWrapper = (props: { children?: ReactNode }) => { const [badgesDialogOpen, setBadgesDialogOpen] = useState(false); @@ -135,9 +135,9 @@ export const cicdContent = ( - {/* + - */} + @@ -147,9 +147,9 @@ export const cicdContent = ( - {/* + - */} + @@ -182,11 +182,11 @@ const cicdCard = ( - {/* + - */} + @@ -228,17 +228,17 @@ const overviewContent = ( {cicdCard} - {/* + Boolean(isGithubInsightsAvailable(e))}> - - + + - + - */} + @@ -248,13 +248,13 @@ const overviewContent = ( - {/* + Boolean(isGithubPullRequestsAvailable(e))}> - */} + @@ -295,13 +295,13 @@ const serviceEntityPage = ( - {/* + - */} + - {/* - - */} + + + @@ -339,13 +339,13 @@ const websiteEntityPage = ( - {/* + - */} + - {/* + - */} + diff --git a/packages/app/src/plugins.ts b/packages/app/src/plugins.ts index ccc7e2a45c..e08bfd6abe 100644 --- a/packages/app/src/plugins.ts +++ b/packages/app/src/plugins.ts @@ -27,19 +27,19 @@ export { plugin as GraphiQL } from '@backstage/plugin-graphiql'; export { plugin as GithubActions } from '@backstage/plugin-github-actions'; export { plugin as Rollbar } from '@backstage/plugin-rollbar'; export { plugin as Newrelic } from '@backstage/plugin-newrelic'; -export { plugin as TravisCI } from '@roadiehq/backstage-plugin-travis-ci'; +export { travisciPlugin } from '@roadiehq/backstage-plugin-travis-ci'; export { plugin as Jenkins } from '@backstage/plugin-jenkins'; export { plugin as ApiDocs } from '@backstage/plugin-api-docs'; -export { plugin as GithubPullRequests } from '@roadiehq/backstage-plugin-github-pull-requests'; +export { githubPullRequestsPlugin } from '@roadiehq/backstage-plugin-github-pull-requests'; export { plugin as GcpProjects } from '@backstage/plugin-gcp-projects'; export { plugin as Kubernetes } from '@backstage/plugin-kubernetes'; export { plugin as Cloudbuild } from '@backstage/plugin-cloudbuild'; export { plugin as CostInsights } from '@backstage/plugin-cost-insights'; -export { plugin as GitHubInsights } from '@roadiehq/backstage-plugin-github-insights'; +export { githubInsightsPlugin } from '@roadiehq/backstage-plugin-github-insights'; export { plugin as CatalogImport } from '@backstage/plugin-catalog-import'; export { plugin as UserSettings } from '@backstage/plugin-user-settings'; export { plugin as PagerDuty } from '@backstage/plugin-pagerduty'; -export { plugin as Buildkite } from '@roadiehq/backstage-plugin-buildkite'; +export { buildkitePlugin } from '@roadiehq/backstage-plugin-buildkite'; export { plugin as Search } from '@backstage/plugin-search'; export { plugin as Org } from '@backstage/plugin-org'; export { plugin as Kafka } from '@backstage/plugin-kafka'; diff --git a/packages/catalog-client/src/CatalogClient.ts b/packages/catalog-client/src/CatalogClient.ts index 7426aabaac..3de25e9808 100644 --- a/packages/catalog-client/src/CatalogClient.ts +++ b/packages/catalog-client/src/CatalogClient.ts @@ -42,10 +42,14 @@ export class CatalogClient implements CatalogApi { } async getLocationById( - id: String, + id: string, options?: CatalogRequestOptions, ): Promise { - return await this.requestOptional('GET', `/locations/${id}`, options); + return await this.requestOptional( + 'GET', + `/locations/${encodeURIComponent(id)}`, + options, + ); } async getEntities( @@ -86,7 +90,9 @@ export class CatalogClient implements CatalogApi { const { kind, namespace = 'default', name } = compoundName; return this.requestOptional( 'GET', - `/entities/by-name/${kind}/${namespace}/${name}`, + `/entities/by-name/${encodeURIComponent(kind)}/${encodeURIComponent( + namespace, + )}/${encodeURIComponent(name)}`, options, ); } @@ -171,14 +177,22 @@ export class CatalogClient implements CatalogApi { id: string, options?: CatalogRequestOptions, ): Promise { - await this.requestIgnored('DELETE', `/locations/${id}`, options); + await this.requestIgnored( + 'DELETE', + `/locations/${encodeURIComponent(id)}`, + options, + ); } async removeEntityByUid( uid: string, options?: CatalogRequestOptions, ): Promise { - await this.requestIgnored('DELETE', `/entities/by-uid/${uid}`, options); + await this.requestIgnored( + 'DELETE', + `/entities/by-uid/${encodeURIComponent(uid)}`, + options, + ); } // diff --git a/packages/catalog-client/src/types.ts b/packages/catalog-client/src/types.ts index 04cbb2b689..0d25bf7483 100644 --- a/packages/catalog-client/src/types.ts +++ b/packages/catalog-client/src/types.ts @@ -46,7 +46,7 @@ export interface CatalogApi { // Locations getLocationById( - id: String, + id: string, options?: CatalogRequestOptions, ): Promise; getOriginLocationByEntity( diff --git a/packages/catalog-model/src/location/helpers.test.ts b/packages/catalog-model/src/location/helpers.test.ts index 888c79b328..3b5994b956 100644 --- a/packages/catalog-model/src/location/helpers.test.ts +++ b/packages/catalog-model/src/location/helpers.test.ts @@ -14,7 +14,11 @@ * limitations under the License. */ -import { parseLocationReference, stringifyLocationReference } from './helpers'; +import { + getEntitySourceLocation, + parseLocationReference, + stringifyLocationReference, +} from './helpers'; describe('parseLocationReference', () => { it('works for the simple case', () => { @@ -68,3 +72,48 @@ describe('stringifyLocationReference', () => { ).toThrow('Unable to stringify location reference, empty target'); }); }); + +describe('getEntitySourceLocation', () => { + it('returns the source-location', () => { + expect( + getEntitySourceLocation({ + apiVersion: 'backstage.io/v1alpha1', + kind: 'Location', + metadata: { + name: 'test', + namespace: 'default', + annotations: { + 'backstage.io/source-location': 'url:https://backstage.io/foo.yaml', + 'backstage.io/managed-by-location': 'url:https://spotify.com', + }, + }, + }), + ).toEqual({ target: 'https://backstage.io/foo.yaml', type: 'url' }); + }); + + it('returns the managed-by-location', () => { + expect( + getEntitySourceLocation({ + apiVersion: 'backstage.io/v1alpha1', + kind: 'Location', + metadata: { + name: 'test', + namespace: 'default', + annotations: { + 'backstage.io/managed-by-location': 'url:https://spotify.com', + }, + }, + }), + ).toEqual({ target: 'https://spotify.com', type: 'url' }); + }); + + it('rejects missing location annotation', () => { + expect(() => + getEntitySourceLocation({ + apiVersion: 'backstage.io/v1alpha1', + kind: 'Location', + metadata: { name: 'test', namespace: 'default' }, + }), + ).toThrow(`Entity 'location:default/test' is missing location`); + }); +}); diff --git a/packages/catalog-model/src/location/helpers.ts b/packages/catalog-model/src/location/helpers.ts index fb1be5abad..5eff598c87 100644 --- a/packages/catalog-model/src/location/helpers.ts +++ b/packages/catalog-model/src/location/helpers.ts @@ -14,6 +14,9 @@ * limitations under the License. */ +import { Entity, stringifyEntityRef } from '../entity'; +import { LOCATION_ANNOTATION, SOURCE_LOCATION_ANNOTATION } from './annotation'; + /** * Parses a string form location reference. * @@ -80,3 +83,26 @@ export function stringifyLocationReference(ref: { return `${type}:${target}`; } + +/** + * Returns the source code location of the Entity, to the extent that one exists. + * + * If the returned location type is of type 'url', the target should be readable at least + * using the UrlReader from @backstage/backend-common. If it is not of type 'url', the caller + * needs to have explicit handling of each location type or signal that it is not supported. + */ +export function getEntitySourceLocation( + entity: Entity, +): { type: string; target: string } { + const locationRef = + entity.metadata?.annotations?.[SOURCE_LOCATION_ANNOTATION] ?? + entity.metadata?.annotations?.[LOCATION_ANNOTATION]; + + if (!locationRef) { + throw new Error( + `Entity '${stringifyEntityRef(entity)}' is missing location`, + ); + } + + return parseLocationReference(locationRef); +} diff --git a/packages/catalog-model/src/location/index.ts b/packages/catalog-model/src/location/index.ts index fddc8bde37..751172c6ba 100644 --- a/packages/catalog-model/src/location/index.ts +++ b/packages/catalog-model/src/location/index.ts @@ -19,7 +19,11 @@ export { ORIGIN_LOCATION_ANNOTATION, SOURCE_LOCATION_ANNOTATION, } from './annotation'; -export { parseLocationReference, stringifyLocationReference } from './helpers'; +export { + parseLocationReference, + stringifyLocationReference, + getEntitySourceLocation, +} from './helpers'; export type { Location, LocationSpec } from './types'; export { analyzeLocationSchema, diff --git a/packages/cli/src/lib/bundler/server.ts b/packages/cli/src/lib/bundler/server.ts index 5fc3a7b5de..24a24d25d2 100644 --- a/packages/cli/src/lib/bundler/server.ts +++ b/packages/cli/src/lib/bundler/server.ts @@ -43,7 +43,7 @@ export async function serveBundle(options: ServeOptions) { const compiler = webpack(config); const server = new WebpackDevServer(compiler, { - hot: true, + hot: !process.env.CI, contentBase: paths.targetPublic, contentBasePublicPath: config.output?.publicPath, publicPath: config.output?.publicPath, diff --git a/packages/core/src/components/ProgressBars/GaugeCard.stories.tsx b/packages/core/src/components/ProgressBars/GaugeCard.stories.tsx index 982999f8d6..5d54e5eda6 100644 --- a/packages/core/src/components/ProgressBars/GaugeCard.stories.tsx +++ b/packages/core/src/components/ProgressBars/GaugeCard.stories.tsx @@ -45,6 +45,9 @@ export const Default = () => ( + + + ); @@ -67,6 +70,14 @@ export const Subhead = () => ( progress={0.89} /> + + + ); @@ -81,5 +92,8 @@ export const LinkInFooter = () => ( + + + ); diff --git a/packages/core/src/components/ProgressBars/GaugeCard.tsx b/packages/core/src/components/ProgressBars/GaugeCard.tsx index 2154619b01..8dcec129c5 100644 --- a/packages/core/src/components/ProgressBars/GaugeCard.tsx +++ b/packages/core/src/components/ProgressBars/GaugeCard.tsx @@ -26,6 +26,7 @@ type Props = { variant?: InfoCardVariants; /** Progress in % specified as decimal, e.g. "0.23" */ progress: number; + inverse?: boolean; deepLink?: BottomLinkProps; }; @@ -38,7 +39,7 @@ const useStyles = makeStyles({ export const GaugeCard = (props: Props) => { const classes = useStyles(props); - const { title, subheader, progress, deepLink, variant } = props; + const { title, subheader, progress, inverse, deepLink, variant } = props; return (
@@ -48,7 +49,7 @@ export const GaugeCard = (props: Props) => { deepLink={deepLink} variant={variant} > - +
); diff --git a/plugins/api-docs/package.json b/plugins/api-docs/package.json index d7f5f3754b..5f56c32f23 100644 --- a/plugins/api-docs/package.json +++ b/plugins/api-docs/package.json @@ -29,7 +29,7 @@ "clean": "backstage-cli clean" }, "dependencies": { - "@asyncapi/react-component": "^0.19.2", + "@asyncapi/react-component": "^0.22.3", "@backstage/catalog-model": "^0.7.5", "@backstage/core": "^0.7.4", "@backstage/plugin-catalog-react": "^0.1.4", diff --git a/plugins/catalog-backend/src/ingestion/processors/ldap/config.test.ts b/plugins/catalog-backend/src/ingestion/processors/ldap/config.test.ts index 5e293766aa..aac9a091b8 100644 --- a/plugins/catalog-backend/src/ingestion/processors/ldap/config.test.ts +++ b/plugins/catalog-backend/src/ingestion/processors/ldap/config.test.ts @@ -172,4 +172,35 @@ describe('readLdapConfig', () => { ]; expect(actual).toEqual(expected); }); + + it('supports multiline ldap query filter', () => { + const config = { + providers: [ + { + target: 'target', + users: { + dn: 'udn', + options: { + filter: ` + (| + (cn=foo bar) + (cn=bar) + ) + `, + }, + }, + groups: { + dn: 'gdn', + options: { + filter: 'f', + }, + }, + }, + ], + }; + const actual = readLdapConfig(new ConfigReader(config)); + + const expected = '(|(cn=foo bar)(cn=bar))'; + expect(actual[0].users.options.filter).toEqual(expected); + }); }); diff --git a/plugins/catalog-backend/src/ingestion/processors/ldap/config.ts b/plugins/catalog-backend/src/ingestion/processors/ldap/config.ts index 7608f247d4..625282ca05 100644 --- a/plugins/catalog-backend/src/ingestion/processors/ldap/config.ts +++ b/plugins/catalog-backend/src/ingestion/processors/ldap/config.ts @@ -182,7 +182,7 @@ export function readLdapConfig(config: Config): LdapProviderConfig[] { } return { scope: c.getOptionalString('scope') as SearchOptions['scope'], - filter: c.getOptionalString('filter'), + filter: formatFilter(c.getOptionalString('filter')), attributes: c.getOptionalStringArray('attributes'), paged: c.getOptionalBoolean('paged'), }; @@ -260,6 +260,11 @@ export function readLdapConfig(config: Config): LdapProviderConfig[] { }; } + function formatFilter(filter?: string): string | undefined { + // Remove extra whitespaces between blocks to support multiline filters from the configuration + return filter?.replace(/\s*(\(|\))/g, '$1')?.trim(); + } + const providerConfigs = config.getOptionalConfigArray('providers') ?? []; return providerConfigs.map(c => { const newConfig = { diff --git a/plugins/catalog/src/CatalogClientWrapper.ts b/plugins/catalog/src/CatalogClientWrapper.ts index 32dff8a0a1..4966d9c13f 100644 --- a/plugins/catalog/src/CatalogClientWrapper.ts +++ b/plugins/catalog/src/CatalogClientWrapper.ts @@ -42,7 +42,7 @@ export class CatalogClientWrapper implements CatalogApi { } async getLocationById( - id: String, + id: string, options?: CatalogRequestOptions, ): Promise { return await this.client.getLocationById(id, { diff --git a/plugins/config-schema/.eslintrc.js b/plugins/config-schema/.eslintrc.js new file mode 100644 index 0000000000..13573efa9c --- /dev/null +++ b/plugins/config-schema/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: [require.resolve('@backstage/cli/config/eslint')], +}; diff --git a/plugins/config-schema/README.md b/plugins/config-schema/README.md new file mode 100644 index 0000000000..7367868e7f --- /dev/null +++ b/plugins/config-schema/README.md @@ -0,0 +1,19 @@ +# config-schema + +The `config-schema` plugin lets you browse a documentation reference of the configuration schema of a particular Backstage installation. It is intended as a tool for integrators rather than something that is useful to end users of Backstage. + +## Usage + +The plugin exports a single full-page extension, the `ConfigSchemaPage`, which you add to an app like a usual top-level tool on a dedicated route. + +It also exports a `configSchemaApiRef` without any default implementation, meaning that an API needs to be registered in the app for the plugin to work. An implementation of the API that is provided out of the box is the `StaticSchemaLoader`, which loads the schema from a URL. It can be added to the app by adding the following to your app's `api.ts`: + +```ts +createApiFactory(configSchemaApiRef, new StaticSchemaLoader()); +``` + +The configuration schema consumed by the `StaticSchemaLoader` can be generated using the following command: + +```shell +yarn --silent backstage-cli config:schema --format=json +``` diff --git a/plugins/config-schema/dev/example-schema.json b/plugins/config-schema/dev/example-schema.json new file mode 100644 index 0000000000..d1e577ff6f --- /dev/null +++ b/plugins/config-schema/dev/example-schema.json @@ -0,0 +1,1659 @@ +{ + "$schema": "https://backstage.io/schema/config-v1", + "title": "Application Configuration Schema", + "type": "object", + "required": ["app", "backend", "costInsights", "sentry", "techdocs"], + "properties": { + "app": { + "type": "object", + "required": ["baseUrl"], + "description": "Generic frontend configuration.", + "properties": { + "baseUrl": { + "type": "string", + "visibility": "frontend", + "description": "The public absolute root URL that the frontend." + }, + "title": { + "type": "string", + "visibility": "frontend", + "description": "The title of the app." + }, + "googleAnalyticsTrackingId": { + "type": "string", + "visibility": "frontend", + "description": "Tracking ID for Google Analytics", + "examples": ["UA-000000-0"] + }, + "listen": { + "type": "object", + "description": "Listening configuration for local development", + "properties": { + "host": { + "type": "string", + "visibility": "frontend", + "description": "The host that the frontend should be bound to. Only used for local development." + }, + "port": { + "type": "number", + "visibility": "frontend", + "description": "The port that the frontend should be bound to. Only used for local development." + } + } + }, + "support": { + "description": "Information about support of this Backstage instance and how to contact the integrator team.", + "type": "object", + "required": ["items", "url"], + "properties": { + "url": { + "description": "The primary support url.", + "visibility": "frontend", + "type": "string" + }, + "items": { + "description": "A list of categorized support item groupings.", + "type": "array", + "items": { + "type": "object", + "required": ["links", "title"], + "properties": { + "title": { + "description": "The title of the support item grouping.", + "visibility": "frontend", + "type": "string" + }, + "icon": { + "description": "An optional icon for the support item grouping.", + "visibility": "frontend", + "type": "string" + }, + "links": { + "description": "A list of support links for the Backstage instance.", + "type": "array", + "items": { + "type": "object", + "required": ["url"], + "properties": { + "url": { + "visibility": "frontend", + "type": "string" + }, + "title": { + "visibility": "frontend", + "type": "string" + } + } + } + } + } + } + } + } + } + } + }, + "lighthouse": { + "type": "object", + "properties": { + "baseUrl": { + "type": "string", + "visibility": "frontend" + } + } + }, + "auth": { + "type": "object", + "description": "Configuration that provides information on available authentication providers configured for app", + "properties": { + "providers": { + "type": "object", + "description": "The available auth-provider options and attributes", + "additionalProperties": { + "type": "object", + "visibility": "frontend" + }, + "properties": { + "google": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "github": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "gitlab": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "saml": { + "type": "object", + "required": ["entryPoint", "issuer"], + "properties": { + "entryPoint": { + "type": "string" + }, + "logoutUrl": { + "type": "string" + }, + "issuer": { + "type": "string" + }, + "cert": { + "type": "string" + }, + "privateKey": { + "type": "string" + }, + "decryptionPvk": { + "type": "string" + }, + "signatureAlgorithm": { + "enum": ["sha256", "sha512"], + "type": "string" + }, + "digestAlgorithm": { + "type": "string" + } + } + }, + "okta": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "oauth2": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": [ + "authorizationUrl", + "clientId", + "clientSecret", + "tokenUrl" + ], + "properties": { + "clientId": { + "type": "string" + }, + "clientSecret": { + "type": "string" + }, + "authorizationUrl": { + "type": "string" + }, + "tokenUrl": { + "type": "string" + }, + "scope": { + "type": "string" + } + } + } + }, + "oidc": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "auth0": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "microsoft": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "onelogin": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "awsalb": { + "type": "object", + "required": ["region"], + "properties": { + "issuer": { + "type": "string" + }, + "region": { + "type": "string" + } + } + } + } + }, + "environment": { + "description": "The 'environment' attribute added as an optional parameter to have configurable environment value for `auth.providers`.\ndefault value: 'development'\noptional values: 'development' | 'production'", + "visibility": "frontend", + "type": "string" + }, + "session": { + "type": "object", + "properties": { + "secret": { + "description": "The secret attribute of session object.", + "visibility": "secret", + "type": "string" + } + } + } + } + }, + "backend": { + "type": "object", + "required": ["baseUrl", "database", "listen"], + "description": "Generic backend configuration.", + "properties": { + "baseUrl": { + "type": "string", + "description": "The public absolute root URL that the backend is reachable at.", + "visibility": "frontend" + }, + "listen": { + "description": "Address that the backend should listen to.", + "anyOf": [ + { + "type": "object", + "properties": { + "address": { + "description": "Address of the interface that the backend should bind to.", + "type": "string" + }, + "port": { + "description": "Port that the backend should listen to.", + "type": ["string", "number"] + } + } + }, + { + "type": "string" + } + ] + }, + "https": { + "description": "HTTPS configuration for the backend. If omitted the backend will serve HTTP.\n\nSetting this to `true` will cause self-signed certificates to be generated, which\ncan be useful for local development or other non-production scenarios.", + "anyOf": [ + { + "type": "object", + "properties": { + "certificate": { + "description": "Certificate configuration", + "type": "object", + "required": ["cert", "key"], + "properties": { + "cert": { + "description": "PEM encoded certificate. Use $file to load in a file", + "type": "string" + }, + "key": { + "description": "PEM encoded certificate key. Use $file to load in a file.", + "visibility": "secret", + "type": "string" + } + } + } + } + }, + { + "enum": [true], + "type": "boolean" + } + ] + }, + "database": { + "description": "Database connection configuration, select database type using the `client` field", + "anyOf": [ + { + "type": "object", + "properties": { + "client": { + "type": "string", + "enum": ["sqlite3"] + }, + "connection": { + "type": "string" + } + }, + "required": ["client", "connection"] + }, + { + "type": "object", + "properties": { + "client": { + "type": "string", + "enum": ["pg"] + }, + "connection": { + "description": "PostgreSQL connection string or knex configuration object.", + "anyOf": [ + { + "type": "object", + "properties": {}, + "additionalProperties": true + }, + { + "type": "string" + } + ] + } + }, + "required": ["client", "connection"] + } + ] + }, + "cors": { + "type": "object", + "properties": { + "origin": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "methods": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "allowedHeaders": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "exposedHeaders": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "credentials": { + "type": "boolean" + }, + "maxAge": { + "type": "number" + }, + "preflightContinue": { + "type": "boolean" + }, + "optionsSuccessStatus": { + "type": "number" + } + } + }, + "reading": { + "description": "Configuration related to URL reading, used for example for reading catalog info\nfiles, scaffolder templates, and techdocs content.", + "type": "object", + "properties": { + "allow": { + "description": "A list of targets to allow outgoing requests to. Users will be able to make\nrequests on behalf of the backend to the targets that are allowed by this list.", + "type": "array", + "items": { + "type": "object", + "required": ["host"], + "properties": { + "host": { + "description": "A host to allow outgoing requests to, being either a full host or\na subdomain wildcard pattern with a leading `*`. For example `example.com`\nand `*.example.com` are valid values, `prod.*.example.com` is not.\nThe host may also contain a port, for example `example.com:8080`.", + "type": "string" + } + } + } + } + } + }, + "csp": { + "description": "Content Security Policy options.\n\nThe keys are the plain policy ID, e.g. \"upgrade-insecure-requests\". The\nvalues are on the format that the helmet library expects them, as an\narray of strings. There is also the special value false, which means to\nremove the default value that Backstage puts in place for that policy.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "enum": [false], + "type": "boolean" + } + ] + } + } + } + }, + "organization": { + "description": "Configuration that provides information about the organization that the app is for.", + "type": "object", + "properties": { + "name": { + "description": "The name of the organization that the app belongs to.", + "visibility": "frontend", + "type": "string" + } + } + }, + "homepage": { + "type": "object", + "properties": { + "clocks": { + "type": "array", + "items": { + "type": "object", + "required": ["label", "timezone"], + "properties": { + "label": { + "visibility": "frontend", + "type": "string" + }, + "timezone": { + "visibility": "frontend", + "type": "string" + } + } + } + } + } + }, + "integrations": { + "description": "Configuration for integrations towards various external repository provider systems", + "type": "object", + "properties": { + "azure": { + "description": "Integration configuration for Azure", + "type": "array", + "items": { + "type": "object", + "required": ["host"], + "properties": { + "host": { + "description": "The hostname of the given Azure instance", + "visibility": "frontend", + "type": "string" + }, + "token": { + "description": "Token used to authenticate requests.", + "visibility": "secret", + "type": "string" + } + } + } + }, + "bitbucket": { + "description": "Integration configuration for Bitbucket", + "type": "array", + "items": { + "type": "object", + "required": ["host"], + "properties": { + "host": { + "description": "The hostname of the given Bitbucket instance", + "visibility": "frontend", + "type": "string" + }, + "token": { + "description": "Token used to authenticate requests.", + "visibility": "secret", + "type": "string" + }, + "apiBaseUrl": { + "description": "The base url for the Bitbucket API, for example https://api.bitbucket.org/2.0", + "visibility": "frontend", + "type": "string" + }, + "username": { + "description": "The username to use for authenticated requests.", + "visibility": "secret", + "type": "string" + }, + "appPassword": { + "description": "Bitbucket app password used to authenticate requests.", + "visibility": "secret", + "type": "string" + } + } + } + }, + "github": { + "description": "Integration configuration for GitHub", + "type": "array", + "items": { + "type": "object", + "required": ["host"], + "properties": { + "host": { + "description": "The hostname of the given GitHub instance", + "visibility": "frontend", + "type": "string" + }, + "token": { + "description": "Token used to authenticate requests.", + "visibility": "secret", + "type": "string" + }, + "apiBaseUrl": { + "description": "The base url for the GitHub API, for example https://api.github.com", + "visibility": "frontend", + "type": "string" + }, + "rawBaseUrl": { + "description": "The base url for GitHub raw resources, for example https://raw.githubusercontent.com", + "visibility": "frontend", + "type": "string" + }, + "apps": { + "description": "GitHub Apps configuration", + "visibility": "backend", + "type": "array", + "items": { + "type": "object", + "required": [ + "appId", + "clientId", + "clientSecret", + "privateKey", + "webhookSecret" + ], + "properties": { + "appId": { + "description": "The numeric GitHub App ID", + "type": "number" + }, + "privateKey": { + "description": "The private key to use for auth against the app", + "visibility": "secret", + "type": "string" + }, + "webhookSecret": { + "description": "The secret used for webhooks", + "visibility": "secret", + "type": "string" + }, + "clientId": { + "description": "The client ID to use", + "type": "string" + }, + "clientSecret": { + "description": "The client secret to use", + "visibility": "secret", + "type": "string" + } + } + } + } + } + } + }, + "gitlab": { + "description": "Integration configuration for GitLab", + "type": "array", + "items": { + "type": "object", + "required": ["host"], + "properties": { + "host": { + "description": "The host of the target that this matches on, e.g. \"gitlab.com\".", + "visibility": "frontend", + "type": "string" + }, + "apiBaseUrl": { + "description": "The base URL of the API of this provider, e.g.\n\"https://gitlab.com/api/v4\", with no trailing slash.\n\nMay be omitted specifically for public GitLab; then it will be deduced.", + "visibility": "frontend", + "type": "string" + }, + "token": { + "description": "The authorization token to use for requests to this provider.\n\nIf no token is specified, anonymous access is used.", + "visibility": "secret", + "type": "string" + }, + "baseUrl": { + "description": "The baseUrl of this provider, e.g. \"https://gitlab.com\", which is\npassed into the GitLab client.\n\nIf no baseUrl is provided, it will default to https://${host}.", + "visibility": "frontend", + "type": "string" + } + } + } + } + } + }, + "catalog": { + "description": "Configuration options for the catalog plugin.", + "type": "object", + "properties": { + "rules": { + "description": "Rules to apply to all catalog entities, from any location.\n\nAn undefined list of matchers means match all, an empty list of\nmatchers means match none.\n\nThis is commonly used to put in what amounts to a whitelist of kinds\nthat regular users of Backstage are permitted to register locations\nfor. This can be used to stop them from registering yaml files\ndescribing for example a Group entity called \"admin\" that they make\nthemselves members of, or similar.", + "type": "array", + "items": { + "type": "object", + "required": ["allow"], + "properties": { + "allow": { + "description": "Allow entities of these particular kinds.\n\nE.g. [\"Component\", \"API\", \"Template\", \"Location\"]", + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, + "readonly": { + "description": "Readonly defines whether the catalog allows writes after startup.\n\nSetting 'readonly=false' allows users to register their own components.\nThis is the default value.\n\nSetting 'readonly=true' configures catalog to only allow reads. This can\nbe used in combination with static locations to only serve operator\nprovided locations. Effectively this removes the ability to register new\ncomponents to a running backstage instance.", + "type": "boolean" + }, + "locations": { + "description": "A set of static locations that the catalog shall always keep itself\nup-to-date with. This is commonly used for large, permanent integrations\nthat are defined by the Backstage operators at an organization, rather\nthan individual things that users register dynamically.\n\nThese have (optional) rules of their own. These override what the global\nrules above specify. This way, you can prevent everybody from register\ne.g. User and Group entities, except for one or a few static locations\nthat have those two kinds explicitly allowed.\n\nFor example:\n\n```yaml\nrules:\n - allow: [Component, API, Template, Location]\nlocations:\n - type: url\n target: https://github.com/org/repo/blob/master/users.yaml\n rules:\n - allow: [User, Group]\n - type: url\n target: https://github.com/org/repo/blob/master/systems.yaml\n rules:\n - allow: [System]\n```", + "type": "array", + "items": { + "type": "object", + "required": ["target", "type"], + "properties": { + "type": { + "description": "The type of location, e.g. \"url\".", + "type": "string" + }, + "target": { + "description": "The target URL of the location, e.g.\n\"https://github.com/org/repo/blob/master/users.yaml\".", + "type": "string" + }, + "rules": { + "description": "Optional extra rules that apply to this particular location.\n\nThese override the global rules above.", + "type": "array", + "items": { + "type": "object", + "required": ["allow"], + "properties": { + "allow": { + "description": "Allow entities of these particular kinds.\n\nE.g. [\"Group\", \"User\"]", + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + }, + "processors": { + "description": "List of processor-specific options and attributes", + "type": "object", + "properties": { + "githubOrg": { + "description": "GithubOrgReaderProcessor configuration", + "type": "object", + "required": ["providers"], + "properties": { + "providers": { + "description": "The configuration parameters for each single GitHub org provider.", + "type": "array", + "items": { + "type": "object", + "required": ["target"], + "properties": { + "target": { + "description": "The prefix of the target that this matches on, e.g.\n\"https://github.com\", with no trailing slash.", + "type": "string" + }, + "apiBaseUrl": { + "description": "The base URL of the API of this provider, e.g.\n\"https://api.github.com\", with no trailing slash.\n\nMay be omitted specifically for GitHub; then it will be deduced.", + "type": "string" + }, + "token": { + "description": "The authorization token to use for requests to this provider.\n\nIf no token is specified, anonymous access is used.", + "visibility": "secret", + "type": "string" + } + } + } + } + } + }, + "ldapOrg": { + "description": "LdapOrgReaderProcessor configuration", + "type": "object", + "required": ["providers"], + "properties": { + "providers": { + "description": "The configuration parameters for each single LDAP provider.", + "type": "array", + "items": { + "type": "object", + "required": ["groups", "target", "users"], + "properties": { + "target": { + "description": "The prefix of the target that this matches on, e.g.\n\"ldaps://ds.example.net\", with no trailing slash.", + "type": "string" + }, + "bind": { + "description": "The settings to use for the bind command. If none are specified,\nthe bind command is not issued.", + "type": "object", + "required": ["dn", "secret"], + "properties": { + "dn": { + "description": "The DN of the user to auth as.\n\nE.g. \"uid=ldap-robot,ou=robots,ou=example,dc=example,dc=net\"", + "type": "string" + }, + "secret": { + "description": "The secret of the user to auth as (its password).", + "visibility": "secret", + "type": "string" + } + } + }, + "users": { + "description": "The settings that govern the reading and interpretation of users.", + "type": "object", + "required": ["dn", "options"], + "properties": { + "dn": { + "description": "The DN under which users are stored.\n\nE.g. \"ou=people,ou=example,dc=example,dc=net\"", + "type": "string" + }, + "options": { + "description": "The search options to use. The default is scope \"one\" and\nattributes \"*\" and \"+\".\n\nIt is common to want to specify a filter, to narrow down the set\nof matching items.", + "type": "object", + "properties": { + "scope": { + "enum": ["base", "one", "sub"], + "type": "string" + }, + "filter": { + "type": "string" + }, + "attributes": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "paged": { + "anyOf": [ + { + "type": "object", + "properties": { + "pageSize": { + "type": "number" + }, + "pagePause": { + "type": "boolean" + } + } + }, + { + "type": "boolean" + } + ] + } + } + }, + "set": { + "description": "JSON paths (on a.b.c form) and hard coded values to set on those\npaths.\n\nThis can be useful for example if you want to hard code a\nnamespace or similar on the generated entities.", + "type": "object" + }, + "map": { + "description": "Mappings from well known entity fields, to LDAP attribute names", + "type": "object", + "properties": { + "rdn": { + "description": "The name of the attribute that holds the relative\ndistinguished name of each entry. Defaults to \"uid\".", + "type": "string" + }, + "name": { + "description": "The name of the attribute that shall be used for the value of\nthe metadata.name field of the entity. Defaults to \"uid\".", + "type": "string" + }, + "description": { + "description": "The name of the attribute that shall be used for the value of\nthe metadata.description field of the entity.", + "type": "string" + }, + "displayName": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.profile.displayName field of the entity. Defaults to\n\"cn\".", + "type": "string" + }, + "email": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.profile.email field of the entity. Defaults to\n\"mail\".", + "type": "string" + }, + "picture": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.profile.picture field of the entity.", + "type": "string" + }, + "memberOf": { + "description": "The name of the attribute that shall be used for the values of\nthe spec.memberOf field of the entity. Defaults to \"memberOf\".", + "type": "string" + } + } + } + } + }, + "groups": { + "description": "The settings that govern the reading and interpretation of groups.", + "type": "object", + "required": ["dn", "options"], + "properties": { + "dn": { + "description": "The DN under which groups are stored.\n\nE.g. \"ou=people,ou=example,dc=example,dc=net\"", + "type": "string" + }, + "options": { + "description": "The search options to use. The default is scope \"one\" and\nattributes \"*\" and \"+\".\n\nIt is common to want to specify a filter, to narrow down the set\nof matching items.", + "type": "object", + "properties": { + "scope": { + "enum": ["base", "one", "sub"], + "type": "string" + }, + "filter": { + "type": "string" + }, + "attributes": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + } + ] + }, + "paged": { + "anyOf": [ + { + "type": "object", + "properties": { + "pageSize": { + "type": "number" + }, + "pagePause": { + "type": "boolean" + } + } + }, + { + "type": "boolean" + } + ] + } + } + }, + "set": { + "description": "JSON paths (on a.b.c form) and hard coded values to set on those\npaths.\n\nThis can be useful for example if you want to hard code a\nnamespace or similar on the generated entities.", + "type": "object" + }, + "map": { + "description": "Mappings from well known entity fields, to LDAP attribute names", + "type": "object", + "properties": { + "rdn": { + "description": "The name of the attribute that holds the relative\ndistinguished name of each entry. Defaults to \"cn\".", + "type": "string" + }, + "name": { + "description": "The name of the attribute that shall be used for the value of\nthe metadata.name field of the entity. Defaults to \"cn\".", + "type": "string" + }, + "description": { + "description": "The name of the attribute that shall be used for the value of\nthe metadata.description field of the entity. Defaults to\n\"description\".", + "type": "string" + }, + "type": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.type field of the entity. Defaults to \"groupType\".", + "type": "string" + }, + "displayName": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.profile.displayName field of the entity. Defaults to\n\"cn\".", + "type": "string" + }, + "email": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.profile.email field of the entity.", + "type": "string" + }, + "picture": { + "description": "The name of the attribute that shall be used for the value of\nthe spec.profile.picture field of the entity.", + "type": "string" + }, + "memberOf": { + "description": "The name of the attribute that shall be used for the values of\nthe spec.parent field of the entity. Defaults to \"memberOf\".", + "type": "string" + }, + "members": { + "description": "The name of the attribute that shall be used for the values of\nthe spec.children field of the entity. Defaults to \"member\".", + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "awsOrganization": { + "description": "AwsOrganizationCloudAccountProcessor configuration", + "type": "object", + "required": ["provider"], + "properties": { + "provider": { + "type": "object", + "properties": { + "roleArn": { + "description": "The role to be assumed by this processor", + "type": "string" + } + } + } + } + }, + "microsoftGraphOrg": { + "description": "MicrosoftGraphOrgReaderProcessor configuration", + "type": "object", + "required": ["providers"], + "properties": { + "providers": { + "description": "The configuration parameters for each single Microsoft Graph provider.", + "type": "array", + "items": { + "type": "object", + "required": [ + "clientId", + "clientSecret", + "target", + "tenantId" + ], + "properties": { + "target": { + "description": "The prefix of the target that this matches on, e.g.\n\"https://graph.microsoft.com/v1.0\", with no trailing slash.", + "type": "string" + }, + "authority": { + "description": "The auth authority used.\n\nDefault value \"https://login.microsoftonline.com\"", + "type": "string" + }, + "tenantId": { + "description": "The tenant whose org data we are interested in.", + "type": "string" + }, + "clientId": { + "description": "The OAuth client ID to use for authenticating requests.", + "type": "string" + }, + "clientSecret": { + "description": "The OAuth client secret to use for authenticating requests.", + "visibility": "secret", + "type": "string" + }, + "userFilter": { + "description": "The filter to apply to extract users.\n\nE.g. \"accountEnabled eq true and userType eq 'member'\"", + "type": "string" + }, + "groupFilter": { + "description": "The filter to apply to extract groups.\n\nE.g. \"securityEnabled eq false and mailEnabled eq true\"", + "type": "string" + } + } + } + } + } + } + } + } + } + }, + "costInsights": { + "type": "object", + "required": ["engineerCost", "products"], + "properties": { + "engineerCost": { + "visibility": "frontend", + "type": "number" + }, + "products": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": ["name"], + "properties": { + "name": { + "visibility": "frontend", + "type": "string" + }, + "icon": { + "visibility": "frontend", + "enum": [ + "compute", + "data", + "database", + "ml", + "search", + "storage" + ], + "type": "string" + } + } + } + }, + "metrics": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": ["name"], + "properties": { + "name": { + "visibility": "frontend", + "type": "string" + }, + "default": { + "visibility": "frontend", + "type": "boolean" + } + } + } + } + } + }, + "fossa": { + "type": "object", + "required": ["organizationId"], + "properties": { + "organizationId": { + "description": "The organization id in fossa.", + "visibility": "frontend", + "type": "string" + } + } + }, + "kubernetes": { + "type": "object", + "required": ["clusterLocatorMethods", "serviceLocatorMethod"], + "properties": { + "serviceLocatorMethod": { + "type": "object", + "required": ["type"], + "visibility": "frontend", + "properties": { + "type": { + "type": "string", + "enum": ["multiTenant"], + "visibility": "frontend" + } + } + }, + "clusterLocatorMethods": { + "type": "array", + "visibility": "frontend" + }, + "customResources": { + "type": "array", + "visibility": "frontend" + } + } + }, + "kafka": { + "type": "object", + "required": ["clientId", "clusters"], + "properties": { + "clientId": { + "description": "Client ID used to Backstage uses to identify when connecting to the Kafka cluster.", + "type": "string" + }, + "clusters": { + "type": "array", + "items": { + "type": "object", + "required": ["brokers", "name"], + "properties": { + "name": { + "type": "string" + }, + "brokers": { + "description": "List of brokers in the Kafka cluster to connect to.", + "type": "array", + "items": { + "type": "string" + } + }, + "ssl": { + "description": "Optional SSL connection parameters to connect to the cluster. Passed directly to Node tls.connect.\nSee https://nodejs.org/dist/latest-v8.x/docs/api/tls.html#tls_tls_createsecurecontext_options", + "anyOf": [ + { + "type": "object", + "properties": { + "ca": { + "type": "array", + "items": { + "type": "string" + } + }, + "key": { + "visibility": "secret", + "type": "string" + }, + "cert": { + "type": "string" + } + }, + "required": ["ca", "cert", "key"] + }, + { + "type": "boolean" + } + ] + }, + "sasl": { + "description": "Optional SASL connection parameters.", + "type": "object", + "required": ["mechanism", "password", "username"], + "properties": { + "mechanism": { + "enum": ["plain", "scram-sha-256", "scram-sha-512"], + "type": "string" + }, + "username": { + "type": "string" + }, + "password": { + "visibility": "secret", + "type": "string" + } + } + } + } + } + } + } + }, + "rollbar": { + "description": "Configuration options for the rollbar-backend plugin", + "type": "object", + "required": ["accountToken"], + "properties": { + "accountToken": { + "description": "The autentication token for accessing the Rollbar API", + "type": "string" + }, + "organization": { + "description": "The Rollbar organization name. This can be omitted by using the `rollbar.com/project-slug` annotation.", + "visibility": "frontend", + "type": "string" + } + } + }, + "proxy": { + "description": "A list of forwarding-proxies. Each key is a route to match,\nbelow the prefix that the proxy plugin is mounted on. It must\nstart with a '/'.", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "object", + "properties": { + "target": { + "description": "Target of the proxy. Url string to be parsed with the url module.", + "type": "string" + }, + "headers": { + "description": "Object with extra headers to be added to target requests.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "changeOrigin": { + "description": "Changes the origin of the host header to the target URL. Default: true.", + "type": "boolean" + }, + "pathRewrite": { + "description": "Rewrite target's url path. Object-keys will be used as RegExp to match paths.\nIf pathRewrite is not specified, it is set to a single rewrite that removes the entire prefix and route.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "allowedMethods": { + "description": "Limit the forwarded HTTP methods, for example allowedMethods: ['GET'] to enforce read-only access.", + "type": "array", + "items": { + "type": "string" + } + }, + "allowedHeaders": { + "description": "Limit the forwarded HTTP methods. By default, only the headers that are considered safe for CORS\nand headers that are set by the proxy will be forwarded.", + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["target"] + }, + { + "type": "string" + } + ] + } + }, + "scaffolder": { + "description": "Configuration options for the scaffolder plugin", + "type": "object", + "properties": { + "github": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "properties": { + "visiblity": { + "description": "The visibility to set on created repositories.", + "enum": ["internal", "private", "public"], + "type": "string" + } + } + }, + "gitlab": { + "type": "object", + "required": ["api"], + "properties": { + "api": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "visiblity": { + "description": "The visibility to set on created repositories.", + "enum": ["internal", "private", "public"], + "type": "string" + } + } + }, + "azure": { + "type": "object", + "required": ["api", "baseUrl"], + "properties": { + "baseUrl": { + "type": "string" + }, + "api": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "bitbucket": { + "type": "object", + "required": ["api"], + "properties": { + "api": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "visiblity": { + "description": "The visibility to set on created repositories.", + "enum": ["private", "public"], + "type": "string" + } + } + } + } + }, + "sonarQube": { + "description": "Optional configurations for the SonarQube plugin", + "type": "object", + "required": ["baseUrl"], + "properties": { + "baseUrl": { + "description": "The base url of the sonarqube installation. Defaults to https://sonarcloud.io.", + "visibility": "frontend", + "type": "string" + } + } + }, + "sentry": { + "description": "Configuration options for the sentry plugin", + "type": "object", + "required": ["organization"], + "properties": { + "organization": { + "description": "The 'organization' attribute", + "visibility": "frontend", + "type": "string" + } + } + }, + "techdocs": { + "description": "Configuration options for the techdocs-backend plugin", + "type": "object", + "required": ["builder"], + "properties": { + "builder": { + "description": "Documentation building process depends on the builder attr", + "visibility": "frontend", + "enum": ["external", "local"], + "type": "string" + }, + "generators": { + "description": "Techdocs generator information", + "type": "object", + "required": ["techdocs"], + "properties": { + "techdocs": { + "enum": ["docker", "local"], + "type": "string" + } + } + }, + "publisher": { + "description": "Techdocs publisher information", + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["local"] + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["awsS3"] + }, + "awsS3": { + "description": "Required when 'type' is set to awsS3", + "type": "object", + "required": ["bucketName"], + "properties": { + "credentials": { + "description": "(Optional) Credentials used to access a storage bucket.\nIf not set, environment variables or aws config file will be used to authenticate.", + "visibility": "secret", + "type": "object", + "required": ["accessKeyId", "secretAccessKey"], + "properties": { + "accessKeyId": { + "description": "User access key id", + "visibility": "secret", + "type": "string" + }, + "secretAccessKey": { + "description": "User secret access key", + "visibility": "secret", + "type": "string" + }, + "roleArn": { + "description": "ARN of role to be assumed", + "visibility": "backend", + "type": "string" + } + } + }, + "bucketName": { + "description": "(Required) Cloud Storage Bucket Name", + "visibility": "backend", + "type": "string" + }, + "region": { + "description": "(Optional) AWS Region.\nIf not set, AWS_REGION environment variable or aws config file will be used.", + "visibility": "secret", + "type": "string" + }, + "endpoint": { + "description": "(Optional) AWS Endpoint.\nThe endpoint URI to send requests to. The default endpoint is built from the configured region.", + "visibility": "secret", + "type": "string" + } + } + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["openStackSwift"] + }, + "openStackSwift": { + "description": "Required when 'type' is set to openStackSwift", + "type": "object", + "required": [ + "authUrl", + "containerName", + "credentials", + "domainId", + "domainName", + "keystoneAuthVersion", + "region" + ], + "properties": { + "credentials": { + "description": "(Required) Credentials used to access a storage bucket.", + "visibility": "secret", + "type": "object", + "required": ["password", "username"], + "properties": { + "username": { + "description": "(Required) Root user name", + "visibility": "secret", + "type": "string" + }, + "password": { + "description": "(Required) Root user password", + "visibility": "secret", + "type": "string" + } + } + }, + "containerName": { + "description": "(Required) Cloud Storage Container Name", + "visibility": "backend", + "type": "string" + }, + "authUrl": { + "description": "(Required) Auth url sometimes OpenStack uses different port check your OpenStack apis.", + "visibility": "backend", + "type": "string" + }, + "keystoneAuthVersion": { + "description": "(Optional) Auth version\nIf not set, 'v2.0' will be used.", + "visibility": "backend", + "type": "string" + }, + "domainId": { + "description": "(Required) Domain Id", + "visibility": "backend", + "type": "string" + }, + "domainName": { + "description": "(Required) Domain Name", + "visibility": "backend", + "type": "string" + }, + "region": { + "description": "(Required) Region", + "visibility": "backend", + "type": "string" + } + } + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["azureBlobStorage"] + }, + "azureBlobStorage": { + "description": "Required when 'type' is set to azureBlobStorage", + "type": "object", + "required": ["containerName", "credentials"], + "properties": { + "credentials": { + "description": "(Required) Credentials used to access a storage container.", + "visibility": "secret", + "type": "object", + "required": ["accountName"], + "properties": { + "accountName": { + "description": "Account access name", + "visibility": "secret", + "type": "string" + }, + "accountKey": { + "description": "(Optional) Account secret primary key\nIf not set, environment variables will be used to authenticate.", + "visibility": "secret", + "type": "string" + } + } + }, + "containerName": { + "description": "(Required) Cloud Storage Container Name", + "visibility": "backend", + "type": "string" + } + } + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["googleGcs"] + }, + "googleGcs": { + "description": "Required when 'type' is set to googleGcs", + "type": "object", + "required": ["bucketName"], + "properties": { + "bucketName": { + "description": "(Required) Cloud Storage Bucket Name", + "visibility": "backend", + "type": "string" + }, + "credentials": { + "description": "(Optional) API key used to write to a storage bucket.\nIf not set, environment variables will be used to authenticate.", + "visibility": "secret", + "type": "string" + } + } + } + }, + "required": ["type"] + } + ] + }, + "requestUrl": { + "visibility": "frontend", + "type": "string" + }, + "storageUrl": { + "type": "string" + } + } + }, + "travisci": { + "description": "Configuration options for the travisci plugin", + "type": "object", + "properties": { + "baseUrl": { + "description": "The 'baseUrl' attribute. It should point to the address of the travis portal.\nIf not provided, frontend plugin will use 'https://travis-ci.com/'", + "visibility": "frontend", + "type": "string" + } + } + } + }, + "description": "This is the schema describing the structure of the app-config.yaml configuration file." +} diff --git a/plugins/config-schema/dev/index.tsx b/plugins/config-schema/dev/index.tsx new file mode 100644 index 0000000000..412f0d283e --- /dev/null +++ b/plugins/config-schema/dev/index.tsx @@ -0,0 +1,42 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDevApp } from '@backstage/dev-utils'; +import { Schema } from 'jsonschema'; +import React from 'react'; +import Observable from 'zen-observable'; +import { configSchemaApiRef } from '../src/api'; +import { ConfigSchemaResult } from '../src/api/types'; +import { ConfigSchemaPage, configSchemaPlugin } from '../src/plugin'; +import exampleSchema from './example-schema.json'; + +createDevApp() + .registerPlugin(configSchemaPlugin) + .registerApi({ + api: configSchemaApiRef, + deps: {}, + factory: () => ({ + schema$: () => + new Observable(sub => + sub.next({ schema: (exampleSchema as unknown) as Schema }), + ), + }), + }) + .addPage({ + element: , + title: 'Root Page', + }) + .render(); diff --git a/plugins/config-schema/package.json b/plugins/config-schema/package.json new file mode 100644 index 0000000000..02e3ac3514 --- /dev/null +++ b/plugins/config-schema/package.json @@ -0,0 +1,51 @@ +{ + "name": "@backstage/plugin-config-schema", + "version": "0.1.1", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "publishConfig": { + "access": "public", + "main": "dist/index.esm.js", + "types": "dist/index.d.ts" + }, + "scripts": { + "build": "backstage-cli plugin:build", + "start": "backstage-cli plugin:serve", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "diff": "backstage-cli plugin:diff", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/config": "^0.1.4", + "@backstage/core": "^0.7.4", + "@backstage/errors": "^0.1.1", + "@backstage/theme": "^0.2.5", + "@material-ui/core": "^4.11.0", + "@material-ui/icons": "^4.9.1", + "@material-ui/lab": "4.0.0-alpha.45", + "jsonschema": "^1.2.6", + "zen-observable": "^0.8.15", + "react": "^16.13.1", + "react-dom": "^16.13.1", + "react-use": "^15.3.3" + }, + "devDependencies": { + "@backstage/cli": "^0.6.7", + "@backstage/dev-utils": "^0.1.13", + "@backstage/test-utils": "^0.1.10", + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/react": "^11.2.5", + "@testing-library/user-event": "^12.0.7", + "@types/jest": "^26.0.7", + "@types/node": "^14.14.32", + "msw": "^0.21.2", + "cross-fetch": "^3.0.6" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/config-schema/src/api/StaticSchemaLoader.ts b/plugins/config-schema/src/api/StaticSchemaLoader.ts new file mode 100644 index 0000000000..ee61370468 --- /dev/null +++ b/plugins/config-schema/src/api/StaticSchemaLoader.ts @@ -0,0 +1,57 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Observable } from '@backstage/core'; +import ObservableImpl from 'zen-observable'; +import { ResponseError } from '@backstage/errors'; +import { Schema } from 'jsonschema'; +import { ConfigSchemaApi, ConfigSchemaResult } from './types'; + +const DEFAULT_URL = 'config-schema.json'; + +/** + * A ConfigSchemaApi implementation that loads the configuration from a URL. + */ +export class StaticSchemaLoader implements ConfigSchemaApi { + private readonly url: string; + + constructor({ url = DEFAULT_URL }: { url?: string } = {}) { + this.url = url; + } + + schema$(): Observable { + return new ObservableImpl(subscriber => { + this.fetchSchema().then( + schema => subscriber.next({ schema }), + error => subscriber.error(error), + ); + }); + } + + private async fetchSchema(): Promise { + const res = await fetch(this.url); + + if (!res.ok) { + if (res.status === 404) { + return undefined; + } + + throw ResponseError.fromResponse(res); + } + + return await res.json(); + } +} diff --git a/plugins/config-schema/src/api/index.ts b/plugins/config-schema/src/api/index.ts new file mode 100644 index 0000000000..eb705b3fa3 --- /dev/null +++ b/plugins/config-schema/src/api/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { configSchemaApiRef } from './types'; +export type { ConfigSchemaApi } from './types'; +export { StaticSchemaLoader } from './StaticSchemaLoader'; diff --git a/plugins/config-schema/src/api/types.ts b/plugins/config-schema/src/api/types.ts new file mode 100644 index 0000000000..025ef76f0c --- /dev/null +++ b/plugins/config-schema/src/api/types.ts @@ -0,0 +1,30 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createApiRef, Observable } from '@backstage/core'; +import { Schema } from 'jsonschema'; + +export interface ConfigSchemaResult { + schema?: Schema; +} + +export interface ConfigSchemaApi { + schema$(): Observable; +} + +export const configSchemaApiRef = createApiRef({ + id: 'plugin.config-schema', +}); diff --git a/plugins/config-schema/src/components/ConfigSchemaPage/ConfigSchemaPage.tsx b/plugins/config-schema/src/components/ConfigSchemaPage/ConfigSchemaPage.tsx new file mode 100644 index 0000000000..a2082ef972 --- /dev/null +++ b/plugins/config-schema/src/components/ConfigSchemaPage/ConfigSchemaPage.tsx @@ -0,0 +1,48 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { useMemo } from 'react'; +import { Header, Page, Content, useApi, Progress } from '@backstage/core'; +import { useObservable } from 'react-use'; +import { configSchemaApiRef } from '../../api'; +import { SchemaViewer } from '../SchemaViewer'; +import { Typography } from '@material-ui/core'; + +export const ConfigSchemaPage = () => { + const configSchemaApi = useApi(configSchemaApiRef); + const schemaResult = useObservable( + useMemo(() => configSchemaApi.schema$(), [configSchemaApi]), + ); + + let content; + if (schemaResult) { + if (schemaResult.schema) { + content = ; + } else { + content = ( + No configuration schema available + ); + } + } else { + content = ; + } + + return ( + +
+ {content} + + ); +}; diff --git a/plugins/config-schema/src/components/ConfigSchemaPage/index.ts b/plugins/config-schema/src/components/ConfigSchemaPage/index.ts new file mode 100644 index 0000000000..e373ae71c6 --- /dev/null +++ b/plugins/config-schema/src/components/ConfigSchemaPage/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { ConfigSchemaPage } from './ConfigSchemaPage'; diff --git a/plugins/config-schema/src/components/SchemaBrowser/SchemaBrowser.tsx b/plugins/config-schema/src/components/SchemaBrowser/SchemaBrowser.tsx new file mode 100644 index 0000000000..52005802b8 --- /dev/null +++ b/plugins/config-schema/src/components/SchemaBrowser/SchemaBrowser.tsx @@ -0,0 +1,196 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createStyles, fade, withStyles } from '@material-ui/core'; +import ChevronRightIcon from '@material-ui/icons/ChevronRight'; +import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; +import { TreeItem, TreeItemProps, TreeView } from '@material-ui/lab'; +import { Schema } from 'jsonschema'; +import React, { ReactNode, useMemo, useRef } from 'react'; +import { useScrollTargets } from '../ScrollTargetsContext'; + +const StyledTreeItem = withStyles(theme => + createStyles({ + label: { + userSelect: 'none', + }, + group: { + marginLeft: 7, + paddingLeft: theme.spacing(1), + borderLeft: `1px solid ${fade(theme.palette.text.primary, 0.15)}`, + }, + }), +)((props: TreeItemProps) => ); + +export function createSchemaBrowserItems( + expanded: string[], + schema: Schema, + path: string = '', + depth: number = 0, +): ReactNode { + let matchArr; + if (schema.anyOf) { + matchArr = schema.anyOf; + } else if (schema.oneOf) { + matchArr = schema.oneOf; + } else if (schema.allOf) { + matchArr = schema.allOf; + } + if (matchArr) { + return matchArr.map((childSchema, index) => { + const childPath = `${path}/${index + 1}`; + if (depth > 0) expanded.push(childPath); + return ( + `} + > + {createSchemaBrowserItems( + expanded, + childSchema, + childPath, + depth + 1, + )} + + ); + }); + } + + switch (schema.type) { + case 'array': { + const childPath = `${path}[]`; + if (depth > 0) expanded.push(childPath); + return ( + + {schema.items && + createSchemaBrowserItems( + expanded, + schema.items as Schema, + childPath, + depth + 1, + )} + + ); + } + case 'object': + case undefined: { + const children = []; + + if (schema.properties) { + children.push( + ...Object.entries(schema.properties).map(([name, childSchema]) => { + const childPath = path ? `${path}.${name}` : name; + if (depth > 0) expanded.push(childPath); + return ( + + {createSchemaBrowserItems( + expanded, + childSchema, + childPath, + depth + 1, + )} + + ); + }), + ); + } + + if (schema.patternProperties) { + children.push( + ...Object.entries(schema.patternProperties).map( + ([name, childSchema]) => { + const childPath = `${path}.<${name}>`; + if (depth > 0) expanded.push(childPath); + return ( + `} + > + {createSchemaBrowserItems( + expanded, + childSchema, + childPath, + depth + 1, + )} + + ); + }, + ), + ); + } + + if (schema.additionalProperties && schema.additionalProperties !== true) { + const childPath = `${path}.*`; + if (depth > 0) expanded.push(childPath); + children.push( + + {createSchemaBrowserItems( + expanded, + schema.additionalProperties, + childPath, + depth + 1, + )} + , + ); + } + + return <>{children}; + } + + default: + return null; + } +} + +export function SchemaBrowser({ schema }: { schema: Schema }) { + const scroll = useScrollTargets(); + const expandedRef = useRef([]); + const data = useMemo(() => { + const expanded = new Array(); + + const items = createSchemaBrowserItems(expanded, schema); + + return { items, expanded }; + }, [schema]); + + if (!scroll) { + throw new Error('No scroll handler available'); + } + + const handleToggle = (_event: unknown, expanded: string[]) => { + expandedRef.current = expanded; + }; + + const handleSelect = (_event: unknown, nodeId: string) => { + if (expandedRef.current.includes(nodeId)) { + scroll.scrollTo(nodeId); + } + }; + + return ( + } + defaultExpandIcon={} + onNodeToggle={handleToggle} + onNodeSelect={handleSelect} + > + {data.items} + + ); +} diff --git a/plugins/config-schema/src/components/SchemaBrowser/index.ts b/plugins/config-schema/src/components/SchemaBrowser/index.ts new file mode 100644 index 0000000000..2b3e8fe79a --- /dev/null +++ b/plugins/config-schema/src/components/SchemaBrowser/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { SchemaBrowser } from './SchemaBrowser'; diff --git a/plugins/config-schema/src/components/SchemaView/ArrayView.tsx b/plugins/config-schema/src/components/SchemaView/ArrayView.tsx new file mode 100644 index 0000000000..15f4dd8800 --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/ArrayView.tsx @@ -0,0 +1,59 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Box, Typography } from '@material-ui/core'; +import { Schema } from 'jsonschema'; +import React from 'react'; +import { ChildView } from './ChildView'; +import { MetadataView } from './MetadataView'; +import { SchemaViewProps } from './types'; + +export function ArrayView({ path, depth, schema }: SchemaViewProps) { + const itemDepth = depth + 1; + const itemPath = path ? `${path}[]` : '[]'; + const itemSchema = schema.items; + + return ( + <> + + {schema.description && ( + + {schema.description} + + )} + + + Items + + {schema.additionalItems && schema.additionalItems !== true && ( + <> + Additional Items + + + )} + + ); +} diff --git a/plugins/config-schema/src/components/SchemaView/ChildView.tsx b/plugins/config-schema/src/components/SchemaView/ChildView.tsx new file mode 100644 index 0000000000..ff970d5251 --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/ChildView.tsx @@ -0,0 +1,123 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { JsonValue } from '@backstage/config'; +import { Box, Chip, Divider, makeStyles, Typography } from '@material-ui/core'; +import { Schema } from 'jsonschema'; +import React, { useEffect, useRef } from 'react'; +import { useScrollTargets } from '../ScrollTargetsContext/ScrollTargetsContext'; +import { SchemaView } from './SchemaView'; + +export interface MetadataViewRowProps { + label: string; + text?: string; + data?: JsonValue; +} + +function titleVariant(depth: number) { + if (depth <= 1) { + return 'h2'; + } else if (depth === 2) { + return 'h3'; + } else if (depth === 3) { + return 'h4'; + } else if (depth === 4) { + return 'h5'; + } + return 'h6'; +} + +const useChildViewStyles = makeStyles(theme => ({ + title: { + marginBottom: 0, + }, + chip: { + marginLeft: theme.spacing(1), + marginRight: 0, + marginBottom: 0, + }, +})); + +export function ChildView({ + path, + depth, + schema, + required, + lastChild, +}: { + path: string; + depth: number; + schema?: Schema; + required?: boolean; + lastChild?: boolean; +}) { + const classes = useChildViewStyles(); + const titleRef = useRef(null); + const scroll = useScrollTargets(); + + useEffect(() => { + return scroll?.setScrollListener(path, () => { + titleRef.current?.scrollIntoView({ behavior: 'smooth' }); + }); + }, [scroll, path]); + + const chips = new Array(); + const chipProps = { size: 'small' as const, classes: { root: classes.chip } }; + + if (required) { + chips.push( + , + ); + } + + const visibility = (schema as { visibility?: string })?.visibility; + if (visibility === 'frontend') { + chips.push( + , + ); + } else if (visibility === 'secret') { + chips.push( + , + ); + } + + return ( + + + + + + {path} + + {chips.length > 0 && } + {chips} + + {schema && ( + + )} + + + ); +} diff --git a/plugins/config-schema/src/components/SchemaView/MatchView.tsx b/plugins/config-schema/src/components/SchemaView/MatchView.tsx new file mode 100644 index 0000000000..db6060b31a --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/MatchView.tsx @@ -0,0 +1,46 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Typography } from '@material-ui/core'; +import { Schema } from 'jsonschema'; +import React from 'react'; +import { ChildView } from './ChildView'; + +export function MatchView({ + path, + depth, + schema, + label, +}: { + path: string; + depth: number; + schema: Schema[]; + label: string; +}) { + return ( + <> + {label} + {schema.map((optionSchema, index) => ( + + ))} + + ); +} diff --git a/plugins/config-schema/src/components/SchemaView/MetadataView.tsx b/plugins/config-schema/src/components/SchemaView/MetadataView.tsx new file mode 100644 index 0000000000..41d48149ad --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/MetadataView.tsx @@ -0,0 +1,110 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { JsonValue } from '@backstage/config'; +import { + Paper, + Table, + TableBody, + TableCell, + TableRow, + Typography, +} from '@material-ui/core'; +import { Schema } from 'jsonschema'; +import React from 'react'; + +export interface MetadataViewRowProps { + label: string; + text?: string; + data?: JsonValue; +} + +export function MetadataViewRow({ label, text, data }: MetadataViewRowProps) { + if (text === undefined && data === undefined) { + return null; + } + return ( + + + + {label} + + + + + {data ? JSON.stringify(data) : text} + + + + ); +} + +export function MetadataView({ schema }: { schema: Schema }) { + return ( + + + + + + {schema.additionalProperties === true && ( + + )} + {schema.additionalItems === true && ( + + )} + + + + + + + + + + + + + + + +
+
+ ); +} diff --git a/plugins/config-schema/src/components/SchemaView/ObjectView.tsx b/plugins/config-schema/src/components/SchemaView/ObjectView.tsx new file mode 100644 index 0000000000..8c72e169d3 --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/ObjectView.tsx @@ -0,0 +1,94 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Box, Typography } from '@material-ui/core'; +import React from 'react'; +import { ChildView } from './ChildView'; +import { MetadataView } from './MetadataView'; +import { SchemaViewProps } from './types'; + +function isRequired(name: string, required?: boolean | string[]) { + if (required === true) { + return true; + } + if (Array.isArray(required)) { + return required.includes(name); + } + return false; +} + +export function ObjectView({ path, depth, schema }: SchemaViewProps) { + const properties = Object.entries(schema.properties ?? {}); + const patternProperties = Object.entries(schema.patternProperties ?? {}); + + return ( + <> + {depth > 0 && ( + + {schema.description && ( + + {schema.description} + + )} + + + )} + {properties.length > 0 && ( + <> + {depth > 0 && Properties} + {properties.map(([name, propSchema], index) => ( + + ))} + + )} + {patternProperties.length > 0 && ( + <> + {depth > 0 && ( + Pattern Properties + )} + {patternProperties.map(([name, propSchema], index) => ( + ` : name} + depth={depth + 1} + schema={propSchema} + lastChild={index === patternProperties.length - 1} + required={isRequired(name, schema.required)} + /> + ))} + + )} + {schema.additionalProperties && schema.additionalProperties !== true && ( + <> + Additional Properties + + + )} + + ); +} diff --git a/plugins/config-schema/src/components/SchemaView/ScalarView.tsx b/plugins/config-schema/src/components/SchemaView/ScalarView.tsx new file mode 100644 index 0000000000..1349358abd --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/ScalarView.tsx @@ -0,0 +1,33 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Box, Typography } from '@material-ui/core'; +import React from 'react'; +import { MetadataView } from './MetadataView'; +import { SchemaViewProps } from './types'; + +export function ScalarView({ schema }: SchemaViewProps) { + return ( + <> + {schema.description && ( + + {schema.description} + + )} + + + ); +} diff --git a/plugins/config-schema/src/components/SchemaView/SchemaView.tsx b/plugins/config-schema/src/components/SchemaView/SchemaView.tsx new file mode 100644 index 0000000000..bf5d7fd18c --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/SchemaView.tsx @@ -0,0 +1,62 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { ArrayView } from './ArrayView'; +import { MatchView } from './MatchView'; +import { ObjectView } from './ObjectView'; +import { ScalarView } from './ScalarView'; +import { SchemaViewProps } from './types'; + +export function SchemaView(props: SchemaViewProps) { + const { schema } = props; + if (schema.anyOf) { + return ( + + ); + } + if (schema.oneOf) { + return ( + + ); + } + if (schema.allOf) { + return ( + + ); + } + switch (schema.type) { + case 'array': + return ; + case 'object': + case undefined: + return ; + default: + return ; + } +} diff --git a/plugins/config-schema/src/components/SchemaView/index.ts b/plugins/config-schema/src/components/SchemaView/index.ts new file mode 100644 index 0000000000..8840696be6 --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { SchemaView } from './SchemaView'; diff --git a/plugins/config-schema/src/components/SchemaView/types.ts b/plugins/config-schema/src/components/SchemaView/types.ts new file mode 100644 index 0000000000..94b676ec3e --- /dev/null +++ b/plugins/config-schema/src/components/SchemaView/types.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Schema } from 'jsonschema'; + +export interface SchemaViewProps { + path: string; + depth: number; + schema: Schema; +} diff --git a/plugins/config-schema/src/components/SchemaViewer/SchemaViewer.test.tsx b/plugins/config-schema/src/components/SchemaViewer/SchemaViewer.test.tsx new file mode 100644 index 0000000000..48dc92098a --- /dev/null +++ b/plugins/config-schema/src/components/SchemaViewer/SchemaViewer.test.tsx @@ -0,0 +1,136 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { render, screen } from '@testing-library/react'; +import { Schema } from 'jsonschema'; +import React from 'react'; +import { SchemaViewer } from './SchemaViewer'; + +describe('SchemaViewer', () => { + it('should render a simple schema', () => { + const schema = { + type: 'object', + properties: { + a: { + description: 'My A', + type: 'string', + }, + b: { + description: 'My B', + type: 'number', + }, + }, + }; + + render(); + + expect(screen.getAllByText('a').length).toBe(2); + expect(screen.getByText('My A')).toBeInTheDocument(); + + expect(screen.getAllByText('b').length).toBe(2); + expect(screen.getByText('My B')).toBeInTheDocument(); + }); + + it('should render complex schema', () => { + const schema: Schema = { + type: 'object', + properties: { + a: { + description: 'My A', + type: 'object', + patternProperties: { + 'prefix.*': { + description: 'Prefix prop', + type: 'string', + }, + }, + additionalProperties: { + description: 'Additional properties for A', + type: 'number', + minimum: 72, + maximum: 79, + }, + }, + b: { + oneOf: [ + { type: 'string', description: 'B one of 1' }, + { + type: 'array', + description: 'B one of 2', + items: { + anyOf: [ + { type: 'string', description: 'Any of B 1' }, + { type: 'number', description: 'Any of B 2' }, + { + type: 'object', + description: 'Any of B 3', + properties: { + deep: { + allOf: [ + { + type: 'number', + description: 'Impossible 1', + }, + { + type: 'boolean', + description: 'Impossible 2', + }, + ], + }, + }, + }, + ], + }, + }, + ], + }, + }, + }; + + render(); + + expect(screen.getAllByText('a').length).toBe(2); + expect(screen.getByText('My A')).toBeInTheDocument(); + expect(screen.getByText('a.')).toBeInTheDocument(); + expect(screen.getByText('Prefix prop')).toBeInTheDocument(); + + expect(screen.getByText('a.*')).toBeInTheDocument(); + expect(screen.getByText('Additional properties for A')).toBeInTheDocument(); + expect(screen.getByText('72')).toBeInTheDocument(); + expect(screen.getByText('79')).toBeInTheDocument(); + + expect(screen.getAllByText('b').length).toBe(2); + expect(screen.getByText('b/1')).toBeInTheDocument(); + expect(screen.getByText('B one of 1')).toBeInTheDocument(); + + expect(screen.getByText('b/2')).toBeInTheDocument(); + expect(screen.getByText('B one of 2')).toBeInTheDocument(); + + expect(screen.getByText('b/2[]')).toBeInTheDocument(); + expect(screen.getByText('b/2[]/1')).toBeInTheDocument(); + expect(screen.getByText('Any of B 1')).toBeInTheDocument(); + expect(screen.getByText('b/2[]/2')).toBeInTheDocument(); + expect(screen.getByText('Any of B 2')).toBeInTheDocument(); + expect(screen.getByText('b/2[]/3')).toBeInTheDocument(); + expect(screen.getByText('Any of B 3')).toBeInTheDocument(); + + expect(screen.getByText('b/2[]/3.deep')).toBeInTheDocument(); + expect(screen.getByText('b/2[]/3.deep/1')).toBeInTheDocument(); + expect(screen.getByText('Impossible 1')).toBeInTheDocument(); + expect(screen.getByText('b/2[]/3.deep/2')).toBeInTheDocument(); + expect(screen.getByText('Impossible 2')).toBeInTheDocument(); + }); +}); diff --git a/plugins/config-schema/src/components/SchemaViewer/SchemaViewer.tsx b/plugins/config-schema/src/components/SchemaViewer/SchemaViewer.tsx new file mode 100644 index 0000000000..3ed3cca0ee --- /dev/null +++ b/plugins/config-schema/src/components/SchemaViewer/SchemaViewer.tsx @@ -0,0 +1,53 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Box, Paper } from '@material-ui/core'; +import { Schema } from 'jsonschema'; +import React from 'react'; +import { SchemaView } from '../SchemaView'; +import { SchemaBrowser } from '../SchemaBrowser'; +import { ScrollTargetsProvider } from '../ScrollTargetsContext/ScrollTargetsContext'; + +export interface SchemaViewerProps { + schema: Schema; +} + +export const SchemaViewer = ({ schema }: SchemaViewerProps) => { + return ( + + + + + + + + + + + + + + + + ); +}; diff --git a/plugins/config-schema/src/components/SchemaViewer/index.ts b/plugins/config-schema/src/components/SchemaViewer/index.ts new file mode 100644 index 0000000000..4852c4e21d --- /dev/null +++ b/plugins/config-schema/src/components/SchemaViewer/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { SchemaViewer } from './SchemaViewer'; diff --git a/plugins/config-schema/src/components/ScrollTargetsContext/ScrollTargetsContext.tsx b/plugins/config-schema/src/components/ScrollTargetsContext/ScrollTargetsContext.tsx new file mode 100644 index 0000000000..085b237754 --- /dev/null +++ b/plugins/config-schema/src/components/ScrollTargetsContext/ScrollTargetsContext.tsx @@ -0,0 +1,52 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { createContext, ReactNode, useContext } from 'react'; + +class ScrollTargetsForwarder { + private readonly listeners = new Map void>(); + + setScrollListener(id: string, listener: () => void): () => void { + this.listeners.set(id, listener); + + return () => { + if (this.listeners.get(id) === listener) { + this.listeners.delete(id); + } + }; + } + + scrollTo(id: string) { + this.listeners.get(id)?.(); + } +} + +const ScrollTargetsContext = createContext( + undefined, +); + +export function ScrollTargetsProvider({ children }: { children: ReactNode }) { + return ( + + ); +} + +export function useScrollTargets() { + return useContext(ScrollTargetsContext); +} diff --git a/plugins/config-schema/src/components/ScrollTargetsContext/index.ts b/plugins/config-schema/src/components/ScrollTargetsContext/index.ts new file mode 100644 index 0000000000..d2d35ec6b1 --- /dev/null +++ b/plugins/config-schema/src/components/ScrollTargetsContext/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { + ScrollTargetsProvider, + useScrollTargets, +} from './ScrollTargetsContext'; diff --git a/plugins/config-schema/src/index.ts b/plugins/config-schema/src/index.ts new file mode 100644 index 0000000000..009b093d50 --- /dev/null +++ b/plugins/config-schema/src/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './api'; +export { configSchemaPlugin, ConfigSchemaPage } from './plugin'; diff --git a/plugins/config-schema/src/plugin.test.ts b/plugins/config-schema/src/plugin.test.ts new file mode 100644 index 0000000000..0f71d800d4 --- /dev/null +++ b/plugins/config-schema/src/plugin.test.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { configSchemaPlugin } from './plugin'; + +describe('config-schema', () => { + it('should export plugin', () => { + expect(configSchemaPlugin).toBeDefined(); + }); +}); diff --git a/plugins/config-schema/src/plugin.ts b/plugins/config-schema/src/plugin.ts new file mode 100644 index 0000000000..841f9f7f04 --- /dev/null +++ b/plugins/config-schema/src/plugin.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createPlugin, createRoutableExtension } from '@backstage/core'; + +import { rootRouteRef } from './routes'; + +export const configSchemaPlugin = createPlugin({ + id: 'config-schema', + routes: { + root: rootRouteRef, + }, +}); + +export const ConfigSchemaPage = configSchemaPlugin.provide( + createRoutableExtension({ + component: () => + import('./components/ConfigSchemaPage').then(m => m.ConfigSchemaPage), + mountPoint: rootRouteRef, + }), +); diff --git a/plugins/config-schema/src/routes.ts b/plugins/config-schema/src/routes.ts new file mode 100644 index 0000000000..8128e1f49f --- /dev/null +++ b/plugins/config-schema/src/routes.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createRouteRef } from '@backstage/core'; + +export const rootRouteRef = createRouteRef({ + title: 'config-schema', +}); diff --git a/plugins/config-schema/src/setupTests.ts b/plugins/config-schema/src/setupTests.ts new file mode 100644 index 0000000000..0cec5b395d --- /dev/null +++ b/plugins/config-schema/src/setupTests.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2021 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '@testing-library/jest-dom'; +import 'cross-fetch/polyfill'; diff --git a/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.ts b/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.ts index 4ae2aff35a..d222bdbce1 100644 --- a/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.ts +++ b/plugins/kubernetes-backend/src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.ts @@ -21,7 +21,7 @@ import { AwsIamKubernetesAuthTranslator } from './AwsIamKubernetesAuthTranslator export class KubernetesAuthTranslatorGenerator { static getKubernetesAuthTranslatorInstance( - authProvider: String, + authProvider: string, ): KubernetesAuthTranslator { switch (authProvider) { case 'google': { diff --git a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts index e76a114d54..7ec1a317d8 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFanOutHandler.test.ts @@ -34,8 +34,8 @@ const mockFetch = (mock: jest.Mock) => { }; function generateMockResourcesAndErrors( - serviceId: String, - clusterName: String, + serviceId: string, + clusterName: string, ) { if (clusterName === 'empty-cluster') { return { diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.test.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.test.ts index fb9d3aeaa6..3b17f46bb3 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.test.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.test.ts @@ -16,6 +16,8 @@ import mockFs from 'mock-fs'; import { Writable } from 'stream'; +import os from 'os'; +import { resolve as resolvePath } from 'path'; import { PullRequestCreator, GithubPullRequestActionInput, @@ -28,7 +30,8 @@ import { getRootLogger } from '@backstage/backend-common'; import { ScmIntegrations } from '@backstage/integration'; import { ConfigReader } from '@backstage/config'; -const id = 'createPublishGithubPullRequestAction'; +const root = os.platform() === 'win32' ? 'C:\\root' : '/root'; +const workspacePath = resolvePath(root, 'my-workspace'); describe('createPublishGithubPullRequestAction', () => { let instance: TemplateAction; @@ -72,7 +75,7 @@ describe('createPublishGithubPullRequestAction', () => { }; mockFs({ - [id]: { 'file.txt': 'Hello there!' }, + [workspacePath]: { 'file.txt': 'Hello there!' }, }); ctx = { @@ -81,7 +84,7 @@ describe('createPublishGithubPullRequestAction', () => { logger: getRootLogger(), logStream: new Writable(), input, - workspacePath: id, + workspacePath, }; }); it('creates a pull request', async () => { @@ -133,7 +136,7 @@ describe('createPublishGithubPullRequestAction', () => { }; mockFs({ - [id]: { + [workspacePath]: { source: { 'foo.txt': 'Hello there!' }, irrelevant: { 'bar.txt': 'Nothing to see here' }, }, @@ -145,7 +148,7 @@ describe('createPublishGithubPullRequestAction', () => { logger: getRootLogger(), logStream: new Writable(), input, - workspacePath: id, + workspacePath, }; }); @@ -188,7 +191,7 @@ describe('createPublishGithubPullRequestAction', () => { }; mockFs({ - [id]: { 'file.txt': 'Hello there!' }, + [workspacePath]: { 'file.txt': 'Hello there!' }, }); ctx = { @@ -197,7 +200,7 @@ describe('createPublishGithubPullRequestAction', () => { logger: getRootLogger(), logStream: new Writable(), input, - workspacePath: id, + workspacePath, }; }); it('creates a pull request', async () => { diff --git a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts index 3a00610a92..e2e4f17efb 100644 --- a/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts +++ b/plugins/scaffolder-backend/src/scaffolder/actions/builtin/publish/githubPullRequest.ts @@ -197,17 +197,21 @@ export const createPublishGithubPullRequestAction = ({ const client = await clientFactory({ integrations, host, owner, repo }); const fileRoot = sourcePath - ? path.join(ctx.workspacePath, sourcePath) + ? path.resolve(ctx.workspacePath, sourcePath) : ctx.workspacePath; - const localFilePaths = await globby(`${fileRoot}/**/*.*`); + + const localFilePaths = await globby(['./**', './**/.*', '!.git'], { + cwd: fileRoot, + gitignore: true, + dot: true, + }); const fileContents = await Promise.all( - localFilePaths.map(p => readFile(p)), + localFilePaths.map(p => readFile(path.resolve(fileRoot, p))), ); - const repoFilePaths = localFilePaths.map(p => { - const relativePath = path.relative(fileRoot, p); - return targetPath ? `${targetPath}/${relativePath}` : relativePath; + const repoFilePaths = localFilePaths.map(repoFilePath => { + return targetPath ? `${targetPath}/${repoFilePath}` : repoFilePath; }); const changes = [ diff --git a/plugins/sonarqube/README.md b/plugins/sonarqube/README.md index a07bb2964d..27fa81066b 100644 --- a/plugins/sonarqube/README.md +++ b/plugins/sonarqube/README.md @@ -67,8 +67,12 @@ proxy: allowedMethods: ['GET'] headers: Authorization: - # Content: 'Basic base64(":")' <-- note the trailing ':' - # Example: Basic bXktYXBpLWtleTo= + # Environmental variable: SONARQUBE_AUTH_HEADER + # Value: 'Basic base64(":")' + # Encode the ":" string using base64 encoder. + # Note the trailing colon (:) at the end of the token. + # Example environmental config: SONARQUBE_AUTH_HEADER=Basic bXktYXBpLWtleTo= + # Fetch the sonar-auth-token from https://sonarcloud.io/account/security/ $env: SONARQUBE_AUTH_HEADER sonarQube: @@ -77,7 +81,14 @@ sonarQube: 5. Get and provide `SONARQUBE_AUTH_HEADER` as env variable (https://sonarcloud.io/account/security or https://docs.sonarqube.org/latest/user-guide/user-token/) -6. Add the `sonarqube.org/project-key` annotation to your entity's `catalog-info.yaml` file: +6. Run the following commands in the root folder of the project to install and compile the changes. + +```yaml +yarn install +yarn tsc +``` + +7. Add the `sonarqube.org/project-key` annotation to the `catalog-info.yaml` file of the target repo for which code quality analysis is needed. ```yaml apiVersion: backstage.io/v1alpha1 diff --git a/plugins/tech-radar/src/components/RadarDescription/RadarDescription.tsx b/plugins/tech-radar/src/components/RadarDescription/RadarDescription.tsx index 20c489f630..3ac4f153be 100644 --- a/plugins/tech-radar/src/components/RadarDescription/RadarDescription.tsx +++ b/plugins/tech-radar/src/components/RadarDescription/RadarDescription.tsx @@ -19,6 +19,7 @@ import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import { Button, DialogActions, DialogContent } from '@material-ui/core'; import LinkIcon from '@material-ui/icons/Link'; +import { MarkdownContent } from '@backstage/core'; export type Props = { open: boolean; @@ -43,7 +44,9 @@ const RadarDescription = (props: Props): JSX.Element => { {title} - {description} + + + {url && (