From c3831661b32a9f3b2347d1af9af29bb3afa625db Mon Sep 17 00:00:00 2001 From: Abraham Schilling Date: Sat, 27 Nov 2021 19:19:25 +0100 Subject: [PATCH] feature: allow the `org` option to be `false` Previously, being part of a certain GitHub org was a hard requirement. The ability to opt out of this behaviour allows granting access to packages for outside collaborators of a repository, and adds the ability to use multiple GitHub orgs in the package access config. --- README.md | 162 +++++++++++----- config.yaml | 18 +- src/constants.ts | 10 + src/server/plugin/AuthCore.ts | 29 ++- src/server/plugin/Config.ts | 10 +- src/server/plugin/Plugin.ts | 67 ++++++- .../plugin/Config/validateConfig.test.ts | 12 ++ test/server/plugin/Core/authenticate.test.ts | 59 +++++- .../Core/createAuthenticatedUser.test.ts | 18 +- test/server/plugin/Plugin/access.test.ts | 176 ++++++++++++++++++ .../server/plugin/Plugin/authenticate.test.ts | 22 ++- test/utils.ts | 5 +- 12 files changed, 500 insertions(+), 88 deletions(-) create mode 100644 test/server/plugin/Plugin/access.test.ts diff --git a/README.md b/README.md index 52c97ddf..21c40ab6 100644 --- a/README.md +++ b/README.md @@ -32,10 +32,11 @@ This is a Verdaccio plugin that offers GitHub OAuth integration for both the bro ### Features -- The Verdaccio login button redirects you to GitHub. If you have access, you return as a logged-in user. Logout works, too. -- The Verdaccio usage info is updated including copy-to-clipboard. -- Use the built-in command-line tool for quick and easy npm configuration. -- Use GitHub organizations, teams, or repositories to configure permissions. +- The Verdaccio login button redirects you to GitHub instead of showing a login form. Logout works, too. +- Login can be limited to members of a certain GitHub org. +- Package access/publish/unpublish can be limited to GitHub orgs, teams, repos, and users. +- The usage info is updated for use with GitHub OAuth. +- A built-in command-line tool helps you configure npm. ### Compatibility @@ -73,44 +74,70 @@ middlewares: auth: github-oauth-ui: - org: GITHUB_ORG # (required) - client-id: GITHUB_CLIENT_ID # (required) - client-secret: GITHUB_CLIENT_SECRET # (required) - enterprise-origin: GITHUB_ENTERPRISE_ORIGIN # (optional) + client-id: GITHUB_CLIENT_ID + client-secret: GITHUB_CLIENT_SECRET + org: GITHUB_ORG + enterprise-origin: GITHUB_ENTERPRISE_ORIGIN # (if you are using an enterprise instance) ``` -#### Notes +#### Using environment variables -- The plugin options can be actual values or the names of environment variables containing the values. -- The plugin options can be specified under either the `middlewares` or the `auth` node. -- The plugin name must be included under both `middlewares` and `auth` nodes. +The plugin options can be actual values or the names of environment variables containing the values. -#### `org` (required) +For example, either of the below will work: +- `client-id: abc` +- `client-id: GITHUB_CLIENT_ID` and set an environment variable `GITHUB_CLIENT_ID=abc`. -Members of this org will be able to authenticate. +The environment variable names can be freely chosen. The above is just an example. -#### `client-id` and `client-secret` (required) +#### `client-id` and `client-secret` (required, string) These values can be obtained from the GitHub OAuth app page at https://github.com/settings/developers. -#### `enterprise-origin` (optional) +#### `org` (required, string | false) -Set this if you are using GitHub Enterprise. Example: `https://github.example.com` +The name of a GitHub org, for example, `n4bb12-oauth-test`. + +If set to a `string`, it limits the ability to log in to Verdaccio to members of +this GitHub org. + +If set to `false`, everybody with a GitHub account can log in. Permissions are +then purely determined by the [package access configuration](https://verdaccio.org/docs/packages/). + +Note that setting this to `false` changes the semantics of `$authenticated` +since everybody can have a GitHub account. To limit package access based on +GitHub orgs, teams, repos, and users, you can use one of the `github/`-prefixed +group names as described below. + +For example, to limit package access to members of a GitHub org, you can use +`github/owner/ORG_NAME` as a permission group. This effectively results in the +same access restrictions as using `$authenticated` with this option set to a +string, except that every GitHub user can log in (but not see or use anything). + +#### `enterprise-origin` (optional, string | false) + +If you are using a GitHub Enterprise instance, set this to the base URL of your +instance, for example: `https://github.example.com`. + +Remove this option, or set it to `false` if you are using the public GitHub. ### Package Access The following groups are added during login and can be used to configure package permissions: - `$authenticated` -- `github/owner/GITHUB_USER` for the user's personal GitHub account -- `github/owner/GITHUB_ORG` for every GitHub org the user is a member of -- `github/owner/GITHUB_ORG/team/GITHUB_TEAM` for every GitHub team the user is a member of -- `github/owner/GITHUB_ORG/repo/GITHUB_REPO` for every GitHub repository the user has access to +- `GITHUB_USER` — the user's login name +- `github/owner/GITHUB_USER` — the user's personal GitHub account +- `github/owner/GITHUB_ORG` — for every GitHub org the user is a member of +- `github/owner/GITHUB_ORG/team/GITHUB_TEAM` — for every GitHub team the user is a member of +- `github/owner/GITHUB_ORG/repo/GITHUB_REPO` — for every GitHub repository the user has access to (including outside collaborators) + +Note that visibility to orgs, org teams, and org repositories requires -These groups are deprecated but still work: +Additionally, the following deprecated groups are added: -- `github/GITHUB_ORG` for every GitHub org the user is a member of -- `github/GITHUB_ORG/GITHUB_TEAM` for every GitHub team the user is a member of +- `github/GITHUB_ORG` — for every GitHub org the user is a member of +- `github/GITHUB_ORG/GITHUB_TEAM` — for every GitHub team the user is a member of You can use these groups as shown below: @@ -126,7 +153,7 @@ packages: # limit actions to team members unpublish: github/owner/GITHUB_ORG/team/GITHUB_TEAM bar: - # limit actions to repository members (does not work for outside collaborators) + # limit actions to repository members (including outside collaborators) access: github/owner/GITHUB_ORG/repo/GITHUB_REPO ``` @@ -149,10 +176,12 @@ See the [global-agent](https://github.com/gajus/global-agent#environment-variabl ### Verdaccio UI - Click the login button and get redirected to GitHub. -- Authorize the registry to access your GitHub user and org info. You only need to do this once. If your org is private, make sure to click the Request or Grant button to get `read:org` access when prompted to authorize. -- Once completed, you'll be redirected back to the Verdaccio registry. - -You are now logged in. +- Authorize the registry to access your GitHub user and org info. +You only need to do this once. If your org is private, make sure to click the +Request or Grant button to get `read:org` access when +prompted to authorize Verdaccio. +- Once completed, you'll be redirected back to Verdaccio. +- You are now logged in 🎉. ### Command Line @@ -186,7 +215,8 @@ $ npm whoami --registry http://localhost:4873 n4bb12 ``` -If you see your GitHub username, you are ready to start installing and publishing packages. +If you see your GitHub username, you are ready to start installing and +publishing packages. ## Logout @@ -196,11 +226,13 @@ Click the Logout button as per usual. ### Command Line -Unless OAuth access is revoked in the GitHub settings, the token is valid indefinitely. +Unless OAuth access is revoked in the GitHub settings, the token is valid +indefinitely. ## Revoke Tokens -To invalidate your active login tokens you need to revoke access on the GitHub OAuth app: +To invalidate your active login tokens you need to revoke access on the GitHub +OAuth app: - Go to https://github.com/settings/applications - Find your Verdaccio app @@ -208,36 +240,70 @@ To invalidate your active login tokens you need to revoke access on the GitHub O ![](screenshots/revoke.png) -If you have created the GitHub OAuth app, you can also revoke access for all users: +If you have created the GitHub OAuth app, you can also revoke access for all +users: - Go to https://github.com/settings/applications - Find your Verdaccio app - Click the app name - On the app detail page click the Revoke all user tokens button - ## Troubleshooting -### "Failed requesting GitHub user info" +### Missing permission groups after logging in -- Double-check that your configured client id and client secret are correct. -- If you are behind a proxy, make sure you are also passing through the query parameters to Verdaccio, see https://github.com/n4bb12/verdaccio-github-oauth-ui/issues/47#issuecomment-643814163 for an `nginx` example. +If the GitHub org or some of its contents are private, users will need to grant +`read:org` permission during login to allow Verdaccio to see this information. + +Users can request or grant this permission during the OAuth flow (i.e. during +first login) by clicking on the Request or Grant button +next to each org when prompted to authorize Verdaccio to access GitHub information. + +If users accidentally skipped this step, go to https://github.com/settings/applications, +find the Verdaccio app, and grant `read:org` access from there. + +### Error: "verdaccio-github-oauth-ui plugin not found" + +Avoid using a global installation of Verdaccio. Despite what Verdaccio examples +or documentation suggest, globally installed plugins may not work. -### Plugin not detected when installed globally +Verdaccio loads plugins by requiring them from various locations. +Global `node_modules` are NOT included in this search because they are NOT part +of the Node.js resolve algorithm. See +[#13](https://github.com/n4bb12/verdaccio-github-oauth-ui/issues/13#issuecomment-435296117) +for more info. -Verdaccio loads plugins by requiring them but global `node_modules` are NOT searched by the node resolve algorithm. Despite what examples or documentation might be suggesting, globally installed plugins are not supported. Some solutions that worked for others: +Solutions that worked for others: + +- Add your global `node_modules` folder to the `NODE_PATH` environment variable. +This hints to Node.js where else to search in addition to default locations. +- Create a `package.json` and install Verdaccio + plugins locally. +- If you are using npm, try using yarn classic. Yarn installs modules a bit +differently such that globally installed plugins are found. +- Deploy Verdaccio by extending the official docker image. It uses a local +Verdaccio installation by default. See `Dockerfile` and `docker.sh` in +[this example](https://gist.github.com/n4bb12/523e8347a580f596cbf14d0d791b5927). + +### Error: "Failed requesting GitHub user info" + +- Double-check that your configured client id and client secret are correct. +- If you are behind a proxy, make sure you are also passing through the query +parameters to Verdaccio. See +[#47](https://github.com/n4bb12/verdaccio-github-oauth-ui/issues/47#issuecomment-643814163) +for an example using `nginx`. -- If you are using npm, switch to yarn. yarn installs modules a bit differently, such that globally installed plugins are found. -- Create a `package.json` and install verdaccio + plugins locally. -- Add your global `node_modules` folder to the `NODE_PATH` environment variable to give Node.js a hint to search for modules here, too. -- Extend the official docker image. See this `docker.sh` and `Dockerfile` in this [example](https://gist.github.com/n4bb12/523e8347a580f596cbf14d0d791b5927). +### Error: "Your auth token is no longer valid. Please log in again." -More info: https://github.com/n4bb12/verdaccio-github-oauth-ui/issues/13#issuecomment-435296117 +If login access is restricted to a certain GitHub org, please see +[missing orgs, teams, repos](missing-orgs-teams-repos) and +[#5](https://github.com/n4bb12/verdaccio-github-oauth-ui/issues/5#issuecomment-417371679). -### "Your auth token is no longer valid. Please log in again." +### Error: "Access denied: User "..." is not a member of "..." -If your GitHub org is private, the org membership visibility might be restricted. If this is the case, your org members need to grant `read:org` permission during login. +If login access is restricted to a certain GitHub org, this could be an expected +error meaning that the user trying to log in is not a member of the required org. -They can request this during fist login by clicking the Request or Grant button when prompted to authorize Verdaccio with GitHub. +See the related [org](#org-required-string-false) plugin option. -If you or a team member accidentally skipped this step, go to https://github.com/settings/applications, find your Verdaccio registry, and grant `read:org` access from there. +If you see this error despite being a member of the configured org, please see +[missing orgs, teams, repos](missing-orgs-teams-repos). diff --git a/config.yaml b/config.yaml index dd58a330..f154f214 100644 --- a/config.yaml +++ b/config.yaml @@ -12,10 +12,10 @@ middlewares: auth: github-oauth-ui: - org: GITHUB_ORG # required, people within this org will be able to authenticate - client-id: GITHUB_CLIENT_ID # required - client-secret: GITHUB_CLIENT_SECRET # required - # enterprise-origin: GITHUB_ENTERPRISE_ORIGIN # optional, set this if you are using github enterprise + client-id: GITHUB_CLIENT_ID + client-secret: GITHUB_CLIENT_SECRET + org: false + enterprise-origin: false htpasswd: file: ./htpasswd @@ -30,9 +30,11 @@ security: packages: "@*/*": - access: $authenticated - publish: $authenticated + access: github/owner/n4bb12-oauth-testing + publish: github/owner/n4bb12-oauth-testing + unpublish: github/owner/n4bb12-oauth-testing "**": - access: $authenticated - publish: $authenticated + access: github/owner/n4bb12-oauth-testing + publish: github/owner/n4bb12-oauth-testing + unpublish: github/owner/n4bb12-oauth-testing diff --git a/src/constants.ts b/src/constants.ts index 4eff4595..4cece302 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -10,3 +10,13 @@ export const cliAuthorizeUrl = "/oauth/authorize" export const publicGitHubOrigin = "https://github.com" export const publicGitHubApiOrigin = "https://api.github.com" + +/** + * See https://verdaccio.org/docs/en/packages + */ +export const authenticatedUserGroups = [ + "$all", + "@all", + "$authenticated", + "@authenticated", +] as const diff --git a/src/server/plugin/AuthCore.ts b/src/server/plugin/AuthCore.ts index 04a419a2..0ef5681a 100644 --- a/src/server/plugin/AuthCore.ts +++ b/src/server/plugin/AuthCore.ts @@ -1,12 +1,13 @@ import uniq from "lodash/uniq" import { stringify } from "querystring" - +import { authenticatedUserGroups } from "../../constants" import { logger } from "../../logger" import { User, Verdaccio } from "../verdaccio" import { Config, getConfig } from "./Config" export class AuthCore { - private readonly requiredOrg = "github/" + getConfig(this.config, "org") + private readonly org = getConfig(this.config, "org") + private readonly requiredGroup = this.org ? "github/owner/" + this.org : null private readonly configuredGroups = this.getConfiguredGroups() constructor( @@ -32,17 +33,22 @@ export class AuthCore { async createAuthenticatedUser( username: string, - providerGroups: string[], + groups: string[], ): Promise { - const relevantGroups = providerGroups.filter( + const relevantGroups = groups.filter( (group) => group in this.configuredGroups, ) - // See https://verdaccio.org/docs/en/packages + relevantGroups.push(username) + + if (this.requiredGroup) { + relevantGroups.push(this.requiredGroup) + } + const user: User = { name: username, - groups: ["$all", "@all", "$authenticated", "@authenticated"], - real_groups: uniq([username, this.requiredOrg, ...relevantGroups]), + groups: [...authenticatedUserGroups], + real_groups: uniq(relevantGroups.filter(Boolean).sort()), } logger.log("Created authenticated user", user) @@ -66,13 +72,18 @@ export class AuthCore { } authenticate(username: string, groups: string[]): boolean { - if (!groups.includes(this.requiredOrg)) { + if (this.requiredGroup && !groups.includes(this.requiredGroup)) { logger.error( - `Access denied: User "${username}" is not a member of "${this.requiredOrg}"`, + `Access denied: User "${username}" is not a member of "${this.requiredGroup}"`, ) return false } + if (!groups.length) { + logger.error(`Access denied: User "${username}" does not have any groups`) + return false + } + return true } } diff --git a/src/server/plugin/Config.ts b/src/server/plugin/Config.ts index e667e789..c18c4056 100644 --- a/src/server/plugin/Config.ts +++ b/src/server/plugin/Config.ts @@ -23,10 +23,10 @@ export type VerdaccioConfig = Omit & { } export interface PluginConfig { - org: string "client-id": string "client-secret": string - "enterprise-origin"?: string + org: string | false + "enterprise-origin"?: string | false } export type PluginConfigKey = keyof PluginConfig @@ -98,7 +98,10 @@ export function validateConfig(config: Config) { validateProp( config, "org", - ow.string.nonEmpty.not.startsWith(publicGitHubOrigin), + ow.any( + ow.string.nonEmpty.not.startsWith(publicGitHubOrigin), + ow.boolean.false, + ), ) validateProp( config, @@ -106,6 +109,7 @@ export function validateConfig(config: Config) { ow.any( ow.undefined, ow.string.url.nonEmpty.not.startsWith(publicGitHubOrigin), + ow.boolean.false, ), ) } diff --git a/src/server/plugin/Plugin.ts b/src/server/plugin/Plugin.ts index b89abeab..932dfe6f 100644 --- a/src/server/plugin/Plugin.ts +++ b/src/server/plugin/Plugin.ts @@ -1,4 +1,11 @@ -import { AuthCallback, IPluginAuth, IPluginMiddleware } from "@verdaccio/types" +import { + AllowAccess, + AuthAccessCallback, + AuthCallback, + IPluginAuth, + IPluginMiddleware, + RemoteUser, +} from "@verdaccio/types" import { Application } from "express" import { CliFlow, WebFlow } from "../flows" @@ -6,7 +13,7 @@ import { GitHubAuthProvider } from "../github" import { Auth, Verdaccio } from "../verdaccio" import { AuthCore } from "./AuthCore" import { Cache } from "./Cache" -import { Config, validateConfig } from "./Config" +import { Config, PackageAccess, validateConfig } from "./Config" import { PatchHtml } from "./PatchHtml" import { registerGlobalProxyAgent } from "./ProxyAgent" import { ServeStatic } from "./ServeStatic" @@ -46,7 +53,11 @@ export class Plugin implements IPluginMiddleware, IPluginAuth { /** * IPluginAuth */ - async authenticate(username: string, token: string, callback: AuthCallback) { + async authenticate( + username: string, + token: string, + callback: AuthCallback, + ): Promise { try { if (!username || !token) { callback(null, false) @@ -67,4 +78,54 @@ export class Plugin implements IPluginMiddleware, IPluginAuth { callback(error, false) } } + + /** + * IPluginAuth + */ + allow_access( + user: RemoteUser, + config: AllowAccess & PackageAccess, + callback: AuthAccessCallback, + ): void { + if (config.access) { + const grant = config.access.some((group) => user.groups.includes(group)) + callback(null, grant) + } else { + callback(null, true) + } + } + + /** + * IPluginAuth + */ + allow_publish( + user: RemoteUser, + config: AllowAccess & PackageAccess, + callback: AuthAccessCallback, + ): void { + if (config.publish) { + const grant = config.publish.some((group) => user.groups.includes(group)) + callback(null, grant) + } else { + this.allow_access(user, config, callback) + } + } + + /** + * IPluginAuth + */ + allow_unpublish( + user: RemoteUser, + config: AllowAccess & PackageAccess, + callback: AuthAccessCallback, + ): void { + if (config.unpublish) { + const grant = config.unpublish.some((group) => + user.groups.includes(group), + ) + callback(null, grant) + } else { + this.allow_publish(user, config, callback) + } + } } diff --git a/test/server/plugin/Config/validateConfig.test.ts b/test/server/plugin/Config/validateConfig.test.ts index b815e0e4..f33fc89b 100644 --- a/test/server/plugin/Config/validateConfig.test.ts +++ b/test/server/plugin/Config/validateConfig.test.ts @@ -105,5 +105,17 @@ describe("Config", () => { user_agent: testUserAgent, }) }) + + it("throws an error if 'org' is true", () => { + shouldFail({ + auth: { + [pluginName]: { ...pluginConfig, ["org"]: true }, + }, + middlewares: { + [pluginName]: { enabled: true }, + }, + user_agent: testUserAgent, + }) + }) }) }) diff --git a/test/server/plugin/Core/authenticate.test.ts b/test/server/plugin/Core/authenticate.test.ts index 1797fc17..a8b6d846 100644 --- a/test/server/plugin/Core/authenticate.test.ts +++ b/test/server/plugin/Core/authenticate.test.ts @@ -1,13 +1,30 @@ +import { pluginName } from "src/constants" import { AuthCore } from "src/server/plugin/AuthCore" -import { createTestAuthCore, testOrg, testUsername } from "test/utils" +import { Config } from "src/server/plugin/Config" +import { + createTestAuthCore, + createTestPluginConfig, + testLoginOrgGroup, + testLoginOrgName, + testUsername, + unrelatedOrgGroup, +} from "test/utils" describe("AuthCore", () => { describe("authenticate", () => { let core: AuthCore - beforeEach(() => { - core = createTestAuthCore() - }) + const configWithMandatoryLoginOrg: Partial = { + auth: { + [pluginName]: createTestPluginConfig({ org: testLoginOrgName }), + }, + } + + const configWithoutMandatoryLoginOrg: Partial = { + auth: { + [pluginName]: createTestPluginConfig({ org: false }), + }, + } function expectAccessGranted(groups: string[]) { const result = core.authenticate(testUsername, groups) @@ -19,14 +36,36 @@ describe("AuthCore", () => { return expect(result).toBe(false) } - it("should grant access", () => { - expectAccessGranted([testOrg]) - expectAccessGranted(["invalid_org", testOrg]) + describe("with mandatory login org", () => { + beforeEach(() => { + core = createTestAuthCore(configWithMandatoryLoginOrg) + }) + + it("should grant login access", () => { + expectAccessGranted([testLoginOrgGroup]) + expectAccessGranted([unrelatedOrgGroup, testLoginOrgGroup]) + }) + + it("should deny login access", () => { + expectAccessDenied([]) + expectAccessDenied([unrelatedOrgGroup]) + }) }) - it("should deny access", () => { - expectAccessDenied([]) - expectAccessDenied(["invalid_org"]) + describe("without mandatory login org", () => { + beforeEach(() => { + core = createTestAuthCore(configWithoutMandatoryLoginOrg) + }) + + it("should grant login access", () => { + expectAccessGranted([testLoginOrgGroup]) + expectAccessGranted([unrelatedOrgGroup, testLoginOrgGroup]) + expectAccessGranted([unrelatedOrgGroup]) + }) + + it("should deny login access", () => { + expectAccessDenied([]) + }) }) }) }) diff --git a/test/server/plugin/Core/createAuthenticatedUser.test.ts b/test/server/plugin/Core/createAuthenticatedUser.test.ts index 741d3f47..f05e6b36 100644 --- a/test/server/plugin/Core/createAuthenticatedUser.test.ts +++ b/test/server/plugin/Core/createAuthenticatedUser.test.ts @@ -37,8 +37,21 @@ describe("AuthCore", () => { `) }) - it("authenticated user real_groups always contain the username and required org", async () => { + it("real_groups always contain the username", async () => { const username = "test-username" + const providerGroups = [] + const core = createTestAuthCore() + + const user = await core.createAuthenticatedUser(username, providerGroups) + + expect(user.real_groups).toMatchInlineSnapshot(` + Array [ + "test-username", + ] + `) + }) + + it("real_groups contains the required login org if configured", async () => { const org = "test-org" const providerGroups = [] const core = createTestAuthCore({ @@ -90,14 +103,13 @@ describe("AuthCore", () => { expect(user.real_groups).toMatchInlineSnapshot(` Array [ - "test-username", - "github/TEST_ORG", "a", "b", "c", "d", "e", "f", + "test-username", ] `) }) diff --git a/test/server/plugin/Plugin/access.test.ts b/test/server/plugin/Plugin/access.test.ts new file mode 100644 index 00000000..979fea46 --- /dev/null +++ b/test/server/plugin/Plugin/access.test.ts @@ -0,0 +1,176 @@ +import { AllowAccess, RemoteUser } from "@verdaccio/types" +import { GitHubAuthProvider } from "src/server/github/AuthProvider" +import { PackageAccess } from "src/server/plugin/Config" +import { Plugin } from "src/server/plugin/Plugin" +import { + createTestAuthProvider, + createTestPackage, + createTestPlugin, + createTestUser, +} from "test/utils" + +jest.mock("src/server/github/AuthProvider") + +const AuthProvider: GitHubAuthProvider & jest.MockInstance = + GitHubAuthProvider as any + +describe("Plugin", () => { + describe("allow_access", () => { + let plugin: Plugin + let user: RemoteUser + let pkg: AllowAccess & PackageAccess + + describe("allow_access", () => { + beforeEach(() => { + AuthProvider.mockImplementation(() => createTestAuthProvider()) + plugin = createTestPlugin() + }) + + it("unprotected packages can be accessed without any permission groups", (done) => { + user = createTestUser([]) + pkg = createTestPackage({}) + + plugin.allow_access(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(true) + done() + }) + }) + + it("protected packages cannot be accessed without the required permission group", (done) => { + user = createTestUser([]) + pkg = createTestPackage({ access: ["required-group"] }) + + plugin.allow_access(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(false) + done() + }) + }) + + it("protected packages can be accessed with the required permission group", (done) => { + user = createTestUser(["required-group"]) + pkg = createTestPackage({ access: ["required-group"] }) + + plugin.allow_access(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(true) + done() + }) + }) + }) + + describe("allow_publish", () => { + beforeEach(() => { + AuthProvider.mockImplementation(() => createTestAuthProvider()) + plugin = createTestPlugin() + }) + + it("unprotected packages can be published without any permission groups", (done) => { + user = createTestUser([]) + pkg = createTestPackage({}) + + plugin.allow_publish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(true) + done() + }) + }) + + it("protected packages cannot be published without the required permission group", (done) => { + user = createTestUser([]) + pkg = createTestPackage({ publish: ["required-group"] }) + + plugin.allow_publish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(false) + done() + }) + }) + + it("protected packages can be published with the required permission group", (done) => { + user = createTestUser(["required-group"]) + pkg = createTestPackage({ publish: ["required-group"] }) + + plugin.allow_publish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(true) + done() + }) + }) + + it("publish protection falls back to access protection", (done) => { + user = createTestUser([]) + pkg = createTestPackage({ access: ["required-group"] }) + + plugin.allow_publish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(false) + done() + }) + }) + }) + + describe("allow_unpublish", () => { + beforeEach(() => { + AuthProvider.mockImplementation(() => createTestAuthProvider()) + plugin = createTestPlugin() + }) + + it("unprotected packages can be unpublished without any permission groups", (done) => { + user = createTestUser([]) + pkg = createTestPackage({}) + + plugin.allow_unpublish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(true) + done() + }) + }) + + it("protected packages cannot be unpublished without the required permission group", (done) => { + user = createTestUser([]) + pkg = createTestPackage({ unpublish: ["required-group"] }) + + plugin.allow_unpublish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(false) + done() + }) + }) + + it("protected packages can be unpublished with the required permission group", (done) => { + user = createTestUser(["required-group"]) + pkg = createTestPackage({ unpublish: ["required-group"] }) + + plugin.allow_unpublish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(true) + done() + }) + }) + + it("unpublish protection falls back to publish protection", (done) => { + user = createTestUser([]) + pkg = createTestPackage({ publish: ["required-group"] }) + + plugin.allow_unpublish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(false) + done() + }) + }) + + it("unpublish protection falls back to access protection", (done) => { + user = createTestUser([]) + pkg = createTestPackage({ access: ["required-group"] }) + + plugin.allow_unpublish(user, pkg, (err, granted) => { + expect(err).toBeNull() + expect(granted).toBe(false) + done() + }) + }) + }) + }) +}) diff --git a/test/server/plugin/Plugin/authenticate.test.ts b/test/server/plugin/Plugin/authenticate.test.ts index b647f5ee..03ecb342 100644 --- a/test/server/plugin/Plugin/authenticate.test.ts +++ b/test/server/plugin/Plugin/authenticate.test.ts @@ -21,10 +21,26 @@ describe("Plugin", () => { plugin = createTestPlugin() }) - it("user with invalid token cannot authenticate", (done) => { - plugin.authenticate(testUsername, "invalid token", (err, groups) => { + it("user with empty username cannot authenticate", (done) => { + plugin.authenticate("", testOAuthToken, (err, groups) => { expect(err).toBeNull() - expect(groups).toEqual(false) + expect(groups).toBe(false) + done() + }) + }) + + it("user with empty token cannot authenticate", (done) => { + plugin.authenticate(testUsername, "", (err, groups) => { + expect(err).toBeNull() + expect(groups).toBe(false) + done() + }) + }) + + it("user with invalid token throws error", (done) => { + plugin.authenticate(testUsername, "invalid_token", (err, groups) => { + expect(err).toBeTruthy() + expect(groups).toBeFalsy() done() }) }) diff --git a/test/utils.ts b/test/utils.ts index 2fbfba04..5e5723da 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -33,13 +33,16 @@ export const testProviderGroups = [ testTeamGroup, testRepoGroup, testUserGroup, + // legacy groups testLegacyOrgGroup, testLegacyTeamGroup, + // unrelated regular groups unrelatedOrgGroup, unrelatedTeamGroup, unrelatedRepoGroup, + // unrelated legacy groups unrelatedLegacyOrgGroup, unrelatedLegacyTeamGroup, @@ -64,9 +67,9 @@ export function createTestPluginConfig( config?: Partial, ): PluginConfig { return { - org: "TEST_ORG", "client-id": testClientId, "client-secret": testClientSecret, + org: false, ...config, } }