Skip to content

Multi project token #6373

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
70 changes: 70 additions & 0 deletions tests/frontend/token_scopes_controller_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/* 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.
*/

/* global expect, beforeEach, describe, it */

import { Application } from "stimulus";
import TokenScopesController from "../../warehouse/static/js/warehouse/controllers/token_scopes_controller";

describe("Confirm controller", () => {
beforeEach(() => {
document.body.innerHTML = `
<div data-controller="token-scopes">
<div>
<input type="radio" name="token_scopes" value="scope:user" id="scope:user" data-action="token-scopes#user" checked>
<label for="scope:user">Entire account (all projects)</label>
</div>
<div>
<input type="radio" name="token_scopes" value="by_project" id="by_project" data-action="token-scopes#project" >
<label for="by_project">By project</label>
</div>
<div>
<input type="checkbox" name="token_scopes" value="scope:project:lunr" id="scope:project:lunr" data-target="token-scopes.selector" disabled>
<label for="scope:project:lunr" class="disabled" data-target="token-scopes.description">lunr</label>
</div>
<div>
<input type="checkbox" name="token_scopes" value="scope:project:tailsocket" id="scope:project:tailsocket" data-target="token-scopes.selector" disabled>
<label for="scope:project:tailsocket" class="disabled" data-target="token-scopes.description">tailsocket</label>
</div>
</div>
`;

const application = Application.start();
application.register("token-scopes", TokenScopesController);
});

describe("clicking the radio button for by project", function () {
it("enables the checkboxes and removes the `disabled` class from descriptions", function () {
document.getElementById("by_project").click();

const checkboxes = document.querySelectorAll("input[type=\"checkbox\"]");
checkboxes.forEach(cb => {
expect(cb).not.toHaveAttribute("disabled");
expect(cb.nextElementSibling).not.toHaveClass("disabled");
});
});
});

describe("clicking the radio button for user scope", function () {
it("disables the checkboxes and adds the `disabled` class from descriptions", function () {
document.getElementById("by_project").click();
document.getElementById("scope:user").click();

const checkboxes = document.querySelectorAll("input[type=\"checkbox\"]");
checkboxes.forEach(cb => {
expect(cb).toHaveAttribute("disabled");
expect(cb.nextElementSibling).toHaveClass("disabled");
});
});
});
});
54 changes: 42 additions & 12 deletions tests/unit/manage/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ def test_creation(self):

def test_validate_description_missing(self):
form = forms.CreateMacaroonForm(
data={"token_scope": "scope:user"},
data={"token_scopes": ["scope:user"]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(),
project_names=pretend.stub(),
Expand All @@ -364,7 +364,7 @@ def test_validate_description_missing(self):

def test_validate_description_in_use(self):
form = forms.CreateMacaroonForm(
data={"description": "dummy", "token_scope": "scope:user"},
data={"description": "dummy", "token_scopes": ["scope:user"]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(
get_macaroon_by_description=lambda *a: pretend.stub()
Expand All @@ -384,63 +384,93 @@ def test_validate_token_scope_missing(self):
)

assert not form.validate()
assert form.token_scope.errors.pop() == "Specify the token scope"
assert form.token_scopes.errors.pop() == "Specify the token scope"

def test_validate_token_scope_unspecified(self):
def test_validate_token_scope_by_project(self):
form = forms.CreateMacaroonForm(
data={"description": "dummy", "token_scope": "scope:unspecified"},
data={"description": "dummy", "token_scopes": ["by_project"]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=pretend.stub(),
)

assert not form.validate()
assert form.token_scope.errors.pop() == "Specify the token scope"
assert form.token_scopes.errors.pop() == "Specify the token scope"

@pytest.mark.parametrize(
("scope"), ["not a real scope", "scope:project", "scope:foo:bar"]
)
def test_validate_token_scope_invalid_format(self, scope):
form = forms.CreateMacaroonForm(
data={"description": "dummy", "token_scope": scope},
data={"description": "dummy", "token_scopes": [scope]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=pretend.stub(),
)

assert not form.validate()
assert form.token_scope.errors.pop() == f"Unknown token scope: {scope}"
assert form.token_scopes.errors.pop() == f"Unknown token scope: {scope}"

def test_validate_token_scope_invalid_project(self):
form = forms.CreateMacaroonForm(
data={"description": "dummy", "token_scope": "scope:project:foo"},
data={"description": "dummy", "token_scopes": ["scope:project:foo"]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=["bar"],
)

assert not form.validate()
assert form.token_scope.errors.pop() == "Unknown or invalid project name: foo"
assert form.token_scopes.errors.pop() == "Unknown or invalid project name: foo"

def test_validate_token_scope_user_and_project(self):
form = forms.CreateMacaroonForm(
data={
"description": "dummy",
"token_scopes": ["scope:project:bar", "scope:user"],
},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=["bar"],
)

assert not form.validate()
assert form.token_scopes.errors.pop() == "Mixed user and project scopes"

def test_validate_token_scope_valid_user(self):
form = forms.CreateMacaroonForm(
data={"description": "dummy", "token_scope": "scope:user"},
data={"description": "dummy", "token_scopes": ["scope:user"]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=pretend.stub(),
)

assert form.validate()
assert form.validated_scope == "user"

def test_validate_token_scope_valid_project(self):
form = forms.CreateMacaroonForm(
data={"description": "dummy", "token_scope": "scope:project:foo"},
data={"description": "dummy", "token_scopes": ["scope:project:foo"]},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=["foo"],
)

assert form.validate()
assert form.validated_scope == {"projects": ["foo"]}

def test_validate_token_scope_valid_projects(self):
form = forms.CreateMacaroonForm(
data={
"description": "dummy",
"token_scopes": ["scope:project:foo", "scope:project:bar"],
},
user_id=pretend.stub(),
macaroon_service=pretend.stub(get_macaroon_by_description=lambda *a: None),
project_names=["foo", "bar"],
)

assert form.validate()
assert form.validated_scope == {"projects": ["foo", "bar"]}


class TestDeleteMacaroonForm:
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/manage/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1573,7 +1573,7 @@ def test_create_macaroon_invalid_form(self, monkeypatch):
create_macaroon=pretend.call_recorder(lambda *a, **kw: pretend.stub())
)
request = pretend.stub(
POST={},
POST=MultiDict({"description": "dummy"}),
user=pretend.stub(id=pretend.stub(), has_primary_verified_email=True),
find_service=lambda interface, **kw: {
IMacaroonService: macaroon_service,
Expand Down Expand Up @@ -1617,7 +1617,7 @@ def test_create_macaroon(self, monkeypatch):
record_event=pretend.call_recorder(lambda *a, **kw: None)
)
request = pretend.stub(
POST={},
POST=MultiDict({"description": "dummy"}),
domain=pretend.stub(),
user=pretend.stub(id=pretend.stub(), has_primary_verified_email=True),
find_service=lambda interface, **kw: {
Expand Down Expand Up @@ -1692,7 +1692,7 @@ def test_create_macaroon_records_events_for_each_project(self, monkeypatch):
record_event = pretend.call_recorder(lambda *a, **kw: None)
user_service = pretend.stub(record_event=record_event)
request = pretend.stub(
POST={},
POST=MultiDict({"description": "dummy"}),
domain=pretend.stub(),
user=pretend.stub(
id=pretend.stub(),
Expand Down
69 changes: 43 additions & 26 deletions warehouse/manage/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def validate_label(self, field):


class CreateMacaroonForm(forms.Form):
__params__ = ["description", "token_scope"]
__params__ = ["description", "token_scopes"]

def __init__(self, *args, user_id, macaroon_service, project_names, **kwargs):
super().__init__(*args, **kwargs)
Expand All @@ -208,8 +208,13 @@ def __init__(self, *args, user_id, macaroon_service, project_names, **kwargs):
]
)

token_scope = wtforms.StringField(
validators=[wtforms.validators.DataRequired(message="Specify the token scope")]
token_scopes = wtforms.FieldList(
wtforms.StringField(
"scope",
validators=[
wtforms.validators.DataRequired(message="Specify the token scope")
],
)
)

def validate_description(self, field):
Expand All @@ -221,34 +226,46 @@ def validate_description(self, field):
):
raise wtforms.validators.ValidationError("API token name already in use")

def validate_token_scope(self, field):
scope = field.data

try:
_, scope_kind = scope.split(":", 1)
except ValueError:
raise wtforms.ValidationError(f"Unknown token scope: {scope}")

if scope_kind == "unspecified":
def validate_token_scopes(self, field):
scopes = field.data
if not scopes:
raise wtforms.ValidationError(f"Specify the token scope")

if scope_kind == "user":
self.validated_scope = scope_kind
if scopes == ["scope:user"]:
self.validated_scope = "user"
return
elif "scope:user" in scopes and len(scopes) > 1:
raise wtforms.ValidationError(f"Mixed user and project scopes")

try:
scope_kind, scope_value = scope_kind.split(":", 1)
except ValueError:
raise wtforms.ValidationError(f"Unknown token scope: {scope}")

if scope_kind != "project":
raise wtforms.ValidationError(f"Unknown token scope: {scope}")
if scope_value not in self.project_names:
raise wtforms.ValidationError(
f"Unknown or invalid project name: {scope_value}"
)
self.validated_scope = {"projects": []}

for scope in scopes:
if scope == "by_project":
# "by_project" is sent to indicate the user made a selection
# of projects either in checkboxes or in the multiselect
continue

self.validated_scope = {"projects": [scope_value]}
try:
_, scope_kind = scope.split(":", 1)
except ValueError:
raise wtforms.ValidationError(f"Unknown token scope: {scope}")

try:
scope_kind, scope_value = scope_kind.split(":", 1)
except ValueError:
raise wtforms.ValidationError(f"Unknown token scope: {scope}")

if scope_kind != "project":
raise wtforms.ValidationError(f"Unknown token scope: {scope}")
if scope_value not in self.project_names:
raise wtforms.ValidationError(
f"Unknown or invalid project name: {scope_value}"
)

self.validated_scope["projects"].append(scope_value)

if not self.validated_scope["projects"]:
raise wtforms.ValidationError(f"Specify the token scope")


class DeleteMacaroonForm(UsernameMixin, PasswordMixin, forms.Form):
Expand Down
3 changes: 2 additions & 1 deletion warehouse/manage/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,8 @@ def create_macaroon(self):
return HTTPSeeOther(self.request.route_path("manage.account"))

form = CreateMacaroonForm(
**self.request.POST,
description=self.request.POST.getone("description"),
token_scopes=self.request.POST.getall("token_scopes"),
user_id=self.request.user.id,
macaroon_service=self.macaroon_service,
project_names=self.project_names,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 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 { Controller } from "stimulus";

export default class extends Controller {

static targets = [ "selector", "description" ];

user() {
this.selectorTargets.forEach(ss => ss.setAttribute("disabled", "disabled"));
this.descriptionTargets.forEach(desc => desc.classList.add("disabled"));
}

project() {
this.selectorTargets.forEach(ss => ss.removeAttribute("disabled"));
this.descriptionTargets.forEach(desc => desc.classList.remove("disabled"));
}
}
5 changes: 5 additions & 0 deletions warehouse/static/sass/blocks/_form-group.scss
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@
max-width: 100%;
}

&__multiselect {
height: 200px;
overflow: auto;
}

&__text {
font-size: $input-font-size;
padding: 4px 0 8px;
Expand Down
Loading