Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for npm owner #4582

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
8 changes: 8 additions & 0 deletions .changeset/grumpy-pots-watch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@verdaccio/types': patch
'@verdaccio/core': patch
'@verdaccio/store': patch
'@verdaccio/api': patch
---

feat: add support for npm owner
2 changes: 2 additions & 0 deletions packages/api/src/package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export default function (route: Router, auth: Auth, storage: Storage): void {
const name = req.params.package;
let version = req.params.version;
const write = req.query.write === 'true';
const username = req?.remote_user?.name;
const abbreviated =
stringUtils.getByQualityPriorityValue(req.get('Accept')) === Storage.ABBREVIATED_HEADER;
const requestOptions = {
Expand All @@ -37,6 +38,7 @@ export default function (route: Router, auth: Auth, storage: Storage): void {
host: req.host,
remoteAddress: req.socket.remoteAddress,
byPassCache: write,
username,
};

try {
Expand Down
37 changes: 31 additions & 6 deletions packages/api/src/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ const debug = buildDebug('verdaccio:api:publish');
*
* 3. Star a package
*
* Permissions: start a package depends of the publish and unpublish permissions, there is no
* specific flag for star or un start.
* Permissions: staring a package depends of the publish and unpublish permissions, there is no
* specific flag for star or unstar.
* The URL for star is similar to the unpublish (change package format)
*
* npm has no endpoint for star a package, rather mutate the metadata and acts as, the difference
* npm has no endpoint for staring a package, rather mutate the metadata and acts as, the difference
* is the users property which is part of the payload and the body only includes
*
* {
Expand All @@ -89,7 +89,24 @@ const debug = buildDebug('verdaccio:api:publish');
"users": {
[username]: boolean value (true, false)
}
}
}
*
* 4. Change owners of a package
*
* Similar to staring a package, changing owners (maintainers) of a package uses the publish
* endpoint.
*
* The body includes a list of the new owners with the following format
*
* {
"_id": pkgName,
"_rev": "4-b0cdaefc9bdb77c8",
"maintainers": [
{ "name": "first owner", "email": "me@verdaccio.org" },
{ "name": "second owner", "email": "you@verdaccio.org" },
...
]
}
*
*/
export default function publish(router: Router, auth: Auth, storage: Storage): void {
Expand Down Expand Up @@ -127,10 +144,11 @@ export default function publish(router: Router, auth: Auth, storage: Storage): v
async function (req: $RequestExtend, res: $ResponseExtend, next: $NextFunctionVer) {
const packageName = req.params.package;
const rev = req.params.revision;
const username = req?.remote_user?.name;

logger.debug({ packageName }, `unpublishing @{packageName}`);
try {
await storage.removePackage(packageName, rev);
await storage.removePackage(packageName, rev, username);
debug('package %s unpublished', packageName);
res.status(HTTP_STATUS.CREATED);
return next({ ok: API_MESSAGE.PKG_REMOVED });
Expand All @@ -155,13 +173,14 @@ export default function publish(router: Router, auth: Auth, storage: Storage): v
): Promise<void> {
const packageName = req.params.package;
const { filename, revision } = req.params;
const username = req?.remote_user?.name;

logger.debug(
{ packageName, filename, revision },
`removing a tarball for @{packageName}-@{tarballName}-@{revision}`
);
try {
await storage.removeTarball(packageName, filename, revision);
await storage.removeTarball(packageName, filename, revision, username);
res.status(HTTP_STATUS.CREATED);

logger.debug(
Expand All @@ -188,6 +207,12 @@ export function publishPackage(storage: Storage): any {
const metadata = req.body;
const username = req?.remote_user?.name;

debug('publishing package %o for user %o', packageName, username);
juanpicado marked this conversation as resolved.
Show resolved Hide resolved
logger.debug(
{ packageName, username },
'publishing package @{packageName} for user @{username}'
);

try {
const message = await storage.updateManifest(metadata, {
name: packageName,
Expand Down
17 changes: 17 additions & 0 deletions packages/api/src/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,22 @@ export default function (route: Router, auth: Auth, config: Config): void {
rateLimit(config?.userRateLimit),
function (req: $RequestExtend, res: Response, next: $NextFunctionVer): void {
debug('verifying user');

if (typeof req.remote_user.name !== 'string' || req.remote_user.name === '') {
debug('user not logged in');
res.status(HTTP_STATUS.OK);
return next({ ok: false });
}

const username = req.params.org_couchdb_user.split(':')[1];
const message = getAuthenticatedMessage(req.remote_user.name);
debug('user authenticated message %o', message);
res.status(HTTP_STATUS.OK);
next({
// 'npm owner' requires user info
juanpicado marked this conversation as resolved.
Show resolved Hide resolved
// TODO: we don't have the email
juanpicado marked this conversation as resolved.
Show resolved Hide resolved
name: username,
email: '',
ok: message,
});
}
Expand Down Expand Up @@ -61,6 +73,10 @@ export default function (route: Router, auth: Auth, config: Config): void {
debug('login or adduser');
const remoteName = req?.remote_user?.name;

if (!validatioUtils.validateUserName(req.params.org_couchdb_user, name)) {
juanpicado marked this conversation as resolved.
Show resolved Hide resolved
return next(errorUtils.getBadRequest(API_ERROR.USERNAME_MISMATCH));
}

if (typeof remoteName !== 'undefined' && typeof name === 'string' && remoteName === name) {
debug('login: no remote user detected');
auth.authenticate(
Expand Down Expand Up @@ -97,6 +113,7 @@ export default function (route: Router, auth: Auth, config: Config): void {
}
);
} else {
debug('adduser: %o', name);
if (
validatioUtils.validatePassword(
password,
Expand Down
33 changes: 32 additions & 1 deletion packages/api/test/integration/_helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
generatePackageMetadata,
initializeServer as initializeServerHelper,
} from '@verdaccio/test-helper';
import { GenericBody, PackageUsers } from '@verdaccio/types';
import { Author, GenericBody, PackageUsers } from '@verdaccio/types';
import { buildToken, generateRandomHexString } from '@verdaccio/utils';

import apiMiddleware from '../../src';
Expand Down Expand Up @@ -142,6 +142,37 @@ export function starPackage(
return test;
}

export function changeOwners(
app,
options: {
maintainers: Author[];
name: string;
_rev: string;
_id?: string;
},
token?: string
): supertest.Test {
const { _rev, _id, maintainers } = options;
const ownerManifest = {
_rev,
_id,
maintainers,
};

const test = supertest(app)
.put(`/${encodeURIComponent(options.name)}`)
.set(HEADER_TYPE.CONTENT_TYPE, HEADERS.JSON)
.send(JSON.stringify(ownerManifest))
.set('accept', HEADERS.GZIP)
.set(HEADER_TYPE.ACCEPT_ENCODING, HEADERS.JSON);

if (typeof token === 'string') {
test.set(HEADERS.AUTHORIZATION, buildToken(TOKEN_BEARER, token));
}

return test;
}

export function getDisTags(app, pkgName) {
return supertest(app)
.get(`/-/package/${encodeURIComponent(pkgName)}/dist-tags`)
Expand Down
24 changes: 24 additions & 0 deletions packages/api/test/integration/config/owner.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
storage: ./storage

auth:
htpasswd:
file: ./htpasswd-owner

web:
enable: true
title: verdaccio

log: { type: stdout, format: pretty, level: info }

# TODO: Add test case for $owner access
packages:
'@*/*':
access: $all
publish: $authenticated
unpublish: $authenticated
'**':
access: $all
publish: $authenticated
unpublish: $authenticated

_debug: true
118 changes: 118 additions & 0 deletions packages/api/test/integration/owner.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/* eslint-disable jest/no-commented-out-tests */
import nock from 'nock';

import { HTTP_STATUS } from '@verdaccio/core';

import {
changeOwners,
createUser,
getPackage,
initializeServer,
publishVersionWithToken,
} from './_helper';

describe('owner', () => {
test.each([['foo', '@scope%2Ffoo']])('should get owner of package', async (pkgName) => {
nock('https://registry.npmjs.org').get(`/${pkgName}`).reply(404);
const app = await initializeServer('owner.yaml');
const credentials = { name: 'test', password: 'test' };
const response = await createUser(app, credentials.name, credentials.password);
expect(response.body.ok).toMatch(`user '${credentials.name}' created`);
await publishVersionWithToken(app, pkgName, '1.0.0', response.body.token).expect(
HTTP_STATUS.CREATED
);

// expect publish to set owner to logged in user
const manifest = await getPackage(app, '', decodeURIComponent(pkgName));
const maintainers = manifest.body.maintainers;
expect(maintainers).toHaveLength(1);
// TODO: This should eventually include the email of the user
expect(maintainers).toEqual([{ name: credentials.name, email: '' }]);
});

test.each([['foo', '@scope%2Ffoo']])('should add/remove owner to package', async (pkgName) => {
nock('https://registry.npmjs.org').get(`/${pkgName}`).reply(404);
const app = await initializeServer('owner.yaml');
const credentials = { name: 'test', password: 'test' };
const firstOwner = { name: 'test', email: '' };
const response = await createUser(app, credentials.name, credentials.password);
expect(response.body.ok).toMatch(`user '${credentials.name}' created`);
await publishVersionWithToken(app, pkgName, '1.0.0', response.body.token).expect(
HTTP_STATUS.CREATED
);

// publish sets owner to logged in user
const manifest = await getPackage(app, '', decodeURIComponent(pkgName));
const maintainers = manifest.body.maintainers;
expect(maintainers).toHaveLength(1);
expect(maintainers).toEqual([firstOwner]);

// add another owner
const secondOwner = { name: 'tester', email: 'test@verdaccio.org' };
const newOwners = [...maintainers, secondOwner];
await changeOwners(
app,
{
_rev: manifest.body._rev,
_id: manifest.body._id,
name: pkgName,
maintainers: newOwners,
},
response.body.token
).expect(HTTP_STATUS.CREATED);

const manifest2 = await getPackage(app, '', decodeURIComponent(pkgName));
const maintainers2 = manifest2.body.maintainers;
expect(maintainers2).toHaveLength(2);
expect(maintainers2).toEqual([firstOwner, secondOwner]);

// remove original owner
await changeOwners(
app,
{
_rev: manifest2.body._rev,
_id: manifest2.body._id,
name: pkgName,
maintainers: [secondOwner],
},
response.body.token
).expect(HTTP_STATUS.CREATED);

const manifest3 = await getPackage(app, '', decodeURIComponent(pkgName));
const maintainers3 = manifest3.body.maintainers;
expect(maintainers3).toHaveLength(1);
expect(maintainers3).toEqual([secondOwner]);
});

test.each([['foo', '@scope%2Ffoo']])('should fail if user is not logged in', async (pkgName) => {
nock('https://registry.npmjs.org').get(`/${pkgName}`).reply(404);
const app = await initializeServer('owner.yaml');
const credentials = { name: 'test', password: 'test' };
const firstOwner = { name: 'test', email: '' };
const response = await createUser(app, credentials.name, credentials.password);
expect(response.body.ok).toMatch(`user '${credentials.name}' created`);
await publishVersionWithToken(app, pkgName, '1.0.0', response.body.token).expect(
HTTP_STATUS.CREATED
);

// publish sets owner to logged in user
const manifest = await getPackage(app, '', decodeURIComponent(pkgName));
const maintainers = manifest.body.maintainers;
expect(maintainers).toHaveLength(1);
expect(maintainers).toEqual([firstOwner]);

// try adding another owner
const secondOwner = { name: 'tester', email: 'test@verdaccio.org' };
const newOwners = [...maintainers, secondOwner];
await changeOwners(
app,
{
_rev: manifest.body._rev,
_id: manifest.body._id,
name: pkgName,
maintainers: newOwners,
},
'' // no token
).expect(HTTP_STATUS.UNAUTHORIZED);
});
});
12 changes: 12 additions & 0 deletions packages/api/test/integration/search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ describe('search', () => {
links: {
npm: '',
},
maintainers: [
{
email: '',
name: 'test',
},
],
name: pkg,
publisher: {},
scope: '',
Expand Down Expand Up @@ -97,6 +103,12 @@ describe('search', () => {
links: {
npm: '',
},
maintainers: [
{
email: '',
name: 'test',
},
],
name: pkg,
publisher: {},
scope: '@scope',
Expand Down