apx-jenkins 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may accept a fee in exchange for,
167
+ acceptance of support, warranty, indemnity, or other liability
168
+ obligations and/or rights consistent with this License. However, in
169
+ accepting such obligations, You may act only on Your own behalf
170
+ and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same page as the copyright notice for easier identification within
187
+ the file itself.
188
+
189
+ Copyright 2026 Fernando Celmer
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: apx-jenkins
3
+ Version: 0.1.0
4
+ Summary: Jenkins for Action Platform: access management through Role-based Authorization Strategy, and read-only tools for jobs, builds and the queue.
5
+ Author-email: Action Platform <cloud@actionplatform.io>
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: action-platform>=0.33
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8; extra == "dev"
13
+ Requires-Dist: ruff>=0.6; extra == "dev"
14
+ Requires-Dist: action-platform[mcp]; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ # apx-jenkins
18
+
19
+ [Jenkins](https://www.jenkins.io) for [Action Platform](https://github.com/actionplatform/action-platform): access management through Role-based Authorization Strategy, and read-only tools for jobs, builds and the build queue.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ action-platform plugin install jenkins
25
+ ```
26
+
27
+ Then fill the options under Plugins, Configure on the platform, or on a machine either export the `AP_JENKINS_*` variables or store the options (`~/.action-platform/plugins/jenkins.json`).
28
+
29
+ | Option | Environment variable | What |
30
+ |---|---|---|
31
+ | `url` | `AP_JENKINS_URL` | The controller's address, e.g. `https://jenkins.example.com` |
32
+ | `user` | `AP_JENKINS_USER` | The Jenkins user id the token belongs to |
33
+ | `token` | `AP_JENKINS_TOKEN` | That user's API token (user menu, Security, API Token) |
34
+
35
+ On a machine the tools and commands read the environment variable first and the options file second. The access capability reads only the options, so a platform keeps the credentials sealed.
36
+
37
+ ### What the token needs
38
+
39
+ - Tools and commands: the user must be able to read the jobs, builds and queue it asks for. They never write.
40
+ - Access: the user must be a Jenkins administrator (Overall/Administer), the [Role-based Authorization Strategy](https://plugins.jenkins.io/role-strategy/) plugin installed, and selected under Manage Jenkins, Security, Authorization. Without it the provider answers with what to install.
41
+
42
+ ## Access
43
+
44
+ The plugin gives the platform's [service access](https://github.com/actionplatform/action-platform/blob/master/docs/concept_service_access.md) a `jenkins` service: who holds which role, drift against the organization's mapping, and grants, revokes and syncs. Accounts are Jenkins user ids; `group:<name>` addresses a group.
45
+
46
+ | Resource | Levels | What it is |
47
+ |---|---|---|
48
+ | `global` | `read`, `admin` | A global role named `read` (Overall/Read, View/Read) or `admin` (Overall/Administer) |
49
+ | `folder/<name>` | `read`, `build`, `configure` | An item role `folder:<name>:<level>` matching the folder and every job in it |
50
+ | `global-role/<name>` | `assigned` | A global role this plugin did not create |
51
+ | `item-role/<name>` | `assigned` | An item role this plugin did not create, such as one that opens a single job |
52
+
53
+ Item roles hold these permissions, each level including the one before it:
54
+
55
+ | Level | Permissions |
56
+ |---|---|
57
+ | `read` | Item/Read, Item/Discover |
58
+ | `build` | `read` + Item/Build, Item/Cancel, Item/Workspace |
59
+ | `configure` | `build` + Item/Configure, Item/Create, Item/Delete, Run/Delete, Run/Update |
60
+
61
+ - A folder is invisible without Overall/Read, so a folder grant also adds `global read` to the account.
62
+ - A role the plugin needs is created on the first grant; a change of level assigns the new role and unassigns the old one.
63
+ - Roles it did not create are read as `global-role/<name>` and `item-role/<name>` with level `assigned`, so an import records them and a sync leaves them alone.
64
+ - An administrator can never be the last one: a change that would leave Jenkins without a global `admin` is refused before anything is sent.
65
+ - Older versions of role-strategy without the user and group assignment calls are served through the generic `assignRole`.
66
+
67
+ ## Tools
68
+
69
+ MCP tools `jenkins_*` and the same reads under `action-platform jenkins`. All are read-only.
70
+
71
+ | Tool | Command | Does |
72
+ |---|---|---|
73
+ | `jenkins_jobs` | `jenkins jobs [folder]` | The jobs of a folder, or of the root: kind, status and the last build's number, result, time and duration. Pass a job path to read that one job. |
74
+ | `jenkins_build` | `jenkins build <job> [number] [--lines N]` | One build, the last when no number is given: result, duration, what started it, branch and revision, and the last `lines` of its console (default 100, at most 2000) with the total. |
75
+ | `jenkins_queue` | `jenkins queue` | What waits in the build queue, since when and why. |
76
+
77
+ A job is addressed by the path Jenkins shows in its URL without the `job/` segments: `team/app`, `team/app/main`.
78
+
79
+ ## Develop
80
+
81
+ ```bash
82
+ pip install -e ".[dev]"
83
+ ruff check . && ruff format --check . && pytest -q
84
+ ```
85
+
86
+ `tests/fake.py` is a controller in memory that answers only what Jenkins answers. `tests/live/` runs read-only against a real controller and is skipped unless `AP_JENKINS_LIVE=1` and `AP_JENKINS_URL`, `AP_JENKINS_USER` and `AP_JENKINS_TOKEN` are set; it changes no role and starts no build.
87
+
88
+ Rules for contributors and agents are in `AGENTS.md`.
@@ -0,0 +1,72 @@
1
+ # apx-jenkins
2
+
3
+ [Jenkins](https://www.jenkins.io) for [Action Platform](https://github.com/actionplatform/action-platform): access management through Role-based Authorization Strategy, and read-only tools for jobs, builds and the build queue.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ action-platform plugin install jenkins
9
+ ```
10
+
11
+ Then fill the options under Plugins, Configure on the platform, or on a machine either export the `AP_JENKINS_*` variables or store the options (`~/.action-platform/plugins/jenkins.json`).
12
+
13
+ | Option | Environment variable | What |
14
+ |---|---|---|
15
+ | `url` | `AP_JENKINS_URL` | The controller's address, e.g. `https://jenkins.example.com` |
16
+ | `user` | `AP_JENKINS_USER` | The Jenkins user id the token belongs to |
17
+ | `token` | `AP_JENKINS_TOKEN` | That user's API token (user menu, Security, API Token) |
18
+
19
+ On a machine the tools and commands read the environment variable first and the options file second. The access capability reads only the options, so a platform keeps the credentials sealed.
20
+
21
+ ### What the token needs
22
+
23
+ - Tools and commands: the user must be able to read the jobs, builds and queue it asks for. They never write.
24
+ - Access: the user must be a Jenkins administrator (Overall/Administer), the [Role-based Authorization Strategy](https://plugins.jenkins.io/role-strategy/) plugin installed, and selected under Manage Jenkins, Security, Authorization. Without it the provider answers with what to install.
25
+
26
+ ## Access
27
+
28
+ The plugin gives the platform's [service access](https://github.com/actionplatform/action-platform/blob/master/docs/concept_service_access.md) a `jenkins` service: who holds which role, drift against the organization's mapping, and grants, revokes and syncs. Accounts are Jenkins user ids; `group:<name>` addresses a group.
29
+
30
+ | Resource | Levels | What it is |
31
+ |---|---|---|
32
+ | `global` | `read`, `admin` | A global role named `read` (Overall/Read, View/Read) or `admin` (Overall/Administer) |
33
+ | `folder/<name>` | `read`, `build`, `configure` | An item role `folder:<name>:<level>` matching the folder and every job in it |
34
+ | `global-role/<name>` | `assigned` | A global role this plugin did not create |
35
+ | `item-role/<name>` | `assigned` | An item role this plugin did not create, such as one that opens a single job |
36
+
37
+ Item roles hold these permissions, each level including the one before it:
38
+
39
+ | Level | Permissions |
40
+ |---|---|
41
+ | `read` | Item/Read, Item/Discover |
42
+ | `build` | `read` + Item/Build, Item/Cancel, Item/Workspace |
43
+ | `configure` | `build` + Item/Configure, Item/Create, Item/Delete, Run/Delete, Run/Update |
44
+
45
+ - A folder is invisible without Overall/Read, so a folder grant also adds `global read` to the account.
46
+ - A role the plugin needs is created on the first grant; a change of level assigns the new role and unassigns the old one.
47
+ - Roles it did not create are read as `global-role/<name>` and `item-role/<name>` with level `assigned`, so an import records them and a sync leaves them alone.
48
+ - An administrator can never be the last one: a change that would leave Jenkins without a global `admin` is refused before anything is sent.
49
+ - Older versions of role-strategy without the user and group assignment calls are served through the generic `assignRole`.
50
+
51
+ ## Tools
52
+
53
+ MCP tools `jenkins_*` and the same reads under `action-platform jenkins`. All are read-only.
54
+
55
+ | Tool | Command | Does |
56
+ |---|---|---|
57
+ | `jenkins_jobs` | `jenkins jobs [folder]` | The jobs of a folder, or of the root: kind, status and the last build's number, result, time and duration. Pass a job path to read that one job. |
58
+ | `jenkins_build` | `jenkins build <job> [number] [--lines N]` | One build, the last when no number is given: result, duration, what started it, branch and revision, and the last `lines` of its console (default 100, at most 2000) with the total. |
59
+ | `jenkins_queue` | `jenkins queue` | What waits in the build queue, since when and why. |
60
+
61
+ A job is addressed by the path Jenkins shows in its URL without the `job/` segments: `team/app`, `team/app/main`.
62
+
63
+ ## Develop
64
+
65
+ ```bash
66
+ pip install -e ".[dev]"
67
+ ruff check . && ruff format --check . && pytest -q
68
+ ```
69
+
70
+ `tests/fake.py` is a controller in memory that answers only what Jenkins answers. `tests/live/` runs read-only against a real controller and is skipped unless `AP_JENKINS_LIVE=1` and `AP_JENKINS_URL`, `AP_JENKINS_USER` and `AP_JENKINS_TOKEN` are set; it changes no role and starts no build.
71
+
72
+ Rules for contributors and agents are in `AGENTS.md`.
@@ -0,0 +1,5 @@
1
+ """Jenkins for Action Platform: access on Role-based Authorization Strategy and read-only tools for jobs, builds and the queue."""
2
+
3
+ from apx_jenkins.plugin import JenkinsPlugin
4
+
5
+ __all__ = ["JenkinsPlugin"]
@@ -0,0 +1,230 @@
1
+ """Jenkins under Role-based Authorization Strategy (the role-strategy plugin): a global role per account, and item roles that open one folder each. A folder is invisible without Overall/Read, so a folder grant asks for global `read` too (`companions`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Optional
7
+
8
+ from action_platform.core.service_access import (
9
+ AccessError,
10
+ AccessProvider,
11
+ Grant,
12
+ Http,
13
+ Op,
14
+ )
15
+
16
+ from apx_jenkins.client import connection
17
+
18
+ BASE = "role-strategy/strategy"
19
+ GLOBAL = "globalRoles"
20
+ ITEMS = "projectRoles"
21
+ GROUP = "group:"
22
+
23
+ GLOBAL_PERMISSIONS = {
24
+ "read": ["hudson.model.Hudson.Read", "hudson.model.View.Read"],
25
+ "admin": ["hudson.model.Hudson.Administer"],
26
+ }
27
+ READ = ["hudson.model.Item.Read", "hudson.model.Item.Discover"]
28
+ BUILD = READ + [
29
+ "hudson.model.Item.Build",
30
+ "hudson.model.Item.Cancel",
31
+ "hudson.model.Item.Workspace",
32
+ ]
33
+ CONFIGURE = BUILD + [
34
+ "hudson.model.Item.Configure",
35
+ "hudson.model.Item.Create",
36
+ "hudson.model.Item.Delete",
37
+ "hudson.model.Run.Delete",
38
+ "hudson.model.Run.Update",
39
+ ]
40
+ FOLDER_PERMISSIONS = {"read": READ, "build": BUILD, "configure": CONFIGURE}
41
+
42
+
43
+ def folder_role(folder: str, level: str) -> str:
44
+ return f"folder:{folder}:{level}"
45
+
46
+
47
+ def folder_pattern(folder: str) -> str:
48
+ return "^" + re.escape(folder) + "(/.*)?$"
49
+
50
+
51
+ class JenkinsProvider(AccessProvider):
52
+ """Accounts are Jenkins user ids (`group:<name>` for a group). `global` is `read` or `admin`; `folder/<name>` is `read`, `build` or `configure` on that folder and every job in it; roles this plugin did not create stay addressable as `global-role/<name>` and `item-role/<name>`."""
53
+
54
+ name = "jenkins"
55
+ levels = {
56
+ "global": ("read", "admin"),
57
+ "folder": ("read", "build", "configure"),
58
+ "global-role": ("assigned",),
59
+ "item-role": ("assigned",),
60
+ }
61
+
62
+ def __init__(
63
+ self, url: str, user: str, token: str, http: Optional[Http] = None
64
+ ) -> None:
65
+ self.http = http or connection(url, user, token)
66
+
67
+ def read(self) -> list[Grant]:
68
+ grants: list[Grant] = []
69
+
70
+ for role, sids in self._roles(GLOBAL).items():
71
+ for account in sids:
72
+ if role in GLOBAL_PERMISSIONS:
73
+ grants.append(Grant("jenkins", account, "global", role))
74
+ else:
75
+ grants.append(
76
+ Grant("jenkins", account, f"global-role/{role}", "assigned")
77
+ )
78
+
79
+ for role, sids in self._roles(ITEMS).items():
80
+ parsed = _folder(role)
81
+
82
+ for account in sids:
83
+ if parsed:
84
+ grants.append(
85
+ Grant("jenkins", account, f"folder/{parsed[0]}", parsed[1])
86
+ )
87
+ else:
88
+ grants.append(
89
+ Grant("jenkins", account, f"item-role/{role}", "assigned")
90
+ )
91
+
92
+ return self.strongest(grants)
93
+
94
+ def apply(self, op: Op) -> None:
95
+ g = op.grant
96
+ kind, _, target = g.resource.partition("/")
97
+
98
+ if kind == "global":
99
+ kind_roles, role, old = GLOBAL, g.level, op.previous
100
+ if op.action != "remove":
101
+ self._ensure(GLOBAL, role, GLOBAL_PERMISSIONS[role])
102
+ elif kind == "folder":
103
+ kind_roles, role = ITEMS, folder_role(target, g.level)
104
+ old = folder_role(target, op.previous) if op.previous else ""
105
+ if op.action != "remove":
106
+ self._ensure(
107
+ ITEMS, role, FOLDER_PERMISSIONS[g.level], folder_pattern(target)
108
+ )
109
+ elif kind in ("global-role", "item-role"):
110
+ kind_roles, role, old = (
111
+ (GLOBAL if kind == "global-role" else ITEMS),
112
+ target,
113
+ "",
114
+ )
115
+ else:
116
+ raise AccessError(f"jenkins: cannot apply {g.resource}")
117
+
118
+ if op.action == "remove":
119
+ self._assign(kind_roles, role, g.account, False)
120
+ return
121
+
122
+ self._assign(kind_roles, role, g.account, True)
123
+
124
+ if op.action == "change" and old and old != role:
125
+ self._assign(kind_roles, old, g.account, False)
126
+
127
+ def companions(self, resource: str) -> list[tuple[str, str]]:
128
+ if self.kind(resource) in ("folder", "item-role"):
129
+ return [("global", "read")]
130
+
131
+ return []
132
+
133
+ def guard(self, ops: list[Op], live: list[Grant]) -> dict[Op, str]:
134
+ admins = {
135
+ g.account.lower()
136
+ for g in live
137
+ if g.resource == "global" and g.level == "admin"
138
+ }
139
+ losing = {
140
+ op.grant.account.lower()
141
+ for op in ops
142
+ if op.grant.resource == "global"
143
+ and op.grant.account.lower() in admins
144
+ and (op.action == "remove" or op.grant.level != "admin")
145
+ }
146
+
147
+ if admins and losing >= admins:
148
+ return {
149
+ op: f"jenkins: {op.grant.account} is the last global admin"
150
+ for op in ops
151
+ if op.grant.resource == "global" and op.grant.account.lower() in losing
152
+ }
153
+
154
+ return {}
155
+
156
+ def _roles(self, kind: str) -> dict[str, list[str]]:
157
+ res = self.http.send("GET", f"{BASE}/getAllRoles", query={"type": kind})
158
+
159
+ if res.status == 404:
160
+ raise AccessError(
161
+ "jenkins: Role-based Authorization Strategy is not active — install the role-strategy plugin and select it under Security"
162
+ )
163
+
164
+ if res.status >= 400 or not isinstance(res.data, dict):
165
+ raise AccessError(f"jenkins: getAllRoles answered {res.status}")
166
+
167
+ return {
168
+ role: [_account(s) for s in sids or []] for role, sids in res.data.items()
169
+ }
170
+
171
+ def _ensure(
172
+ self, kind: str, role: str, permissions: list[str], pattern: str = ""
173
+ ) -> None:
174
+ res = self.http.send(
175
+ "GET", f"{BASE}/getRole", query={"type": kind, "roleName": role}
176
+ )
177
+
178
+ if res.status == 200 and isinstance(res.data, dict) and res.data:
179
+ return
180
+
181
+ form = {
182
+ "type": kind,
183
+ "roleName": role,
184
+ "permissionIds": ",".join(permissions),
185
+ "overwrite": "false",
186
+ }
187
+
188
+ if pattern:
189
+ form["pattern"] = pattern
190
+
191
+ self.http.call("POST", f"{BASE}/addRole", form=form)
192
+
193
+ def _assign(self, kind: str, role: str, account: str, on: bool) -> None:
194
+ verb = "assign" if on else "unassign"
195
+
196
+ if account.startswith(GROUP):
197
+ name, field, sid = f"{verb}GroupRole", "group", account[len(GROUP) :]
198
+ else:
199
+ name, field, sid = f"{verb}UserRole", "user", account
200
+
201
+ res = self.http.send(
202
+ "POST", f"{BASE}/{name}", form={"type": kind, "roleName": role, field: sid}
203
+ )
204
+
205
+ if res.status == 404:
206
+ self.http.call(
207
+ "POST",
208
+ f"{BASE}/{verb}Role",
209
+ form={"type": kind, "roleName": role, "sid": sid},
210
+ )
211
+ elif res.status >= 400:
212
+ raise AccessError(f"jenkins: {name} {role} answered {res.status}")
213
+
214
+
215
+ def _account(sid: Any) -> str:
216
+ if isinstance(sid, dict):
217
+ name = str(sid.get("sid", ""))
218
+
219
+ return GROUP + name if str(sid.get("type", "")).upper() == "GROUP" else name
220
+
221
+ return str(sid)
222
+
223
+
224
+ def _folder(role: str) -> Optional[tuple[str, str]]:
225
+ parts = role.split(":")
226
+
227
+ if len(parts) == 3 and parts[0] == "folder" and parts[2] in FOLDER_PERMISSIONS:
228
+ return parts[1], parts[2]
229
+
230
+ return None
@@ -0,0 +1,48 @@
1
+ """`action-platform jenkins …` — the same reads as the tools, from a terminal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import typer
8
+
9
+ from apx_jenkins.settings import connect
10
+
11
+ app = typer.Typer(help="Jenkins: jobs, builds, the queue.", no_args_is_help=True)
12
+ options: Any | None = None
13
+
14
+
15
+ @app.command("jobs")
16
+ def jobs(
17
+ folder: str = typer.Argument("", help="Folder path; the root when empty"),
18
+ ) -> None:
19
+ """List the jobs of a folder with their last build."""
20
+ for j in connect(options).jobs(folder):
21
+ last = f"#{j.last_number} {j.last_result} {j.last_at}" if j.last_number else "-"
22
+ typer.echo(f"{j.name}\t{j.kind}\t{j.status or '-'}\t{last}")
23
+
24
+
25
+ @app.command("build")
26
+ def build(
27
+ job: str,
28
+ number: int = typer.Argument(0, help="Build number; the last when 0"),
29
+ lines: int = typer.Option(100, help="Console lines from the end"),
30
+ ) -> None:
31
+ """One build and the tail of its console."""
32
+ b = connect(options).build(job, number, lines)
33
+ typer.echo(f"{b.name}\t{b.result}\t{b.started_at}\t{b.duration_s}s")
34
+ typer.echo(f"causes: {'; '.join(b.causes) or '-'}")
35
+ typer.echo(f"revision: {b.revision or '-'} {b.branch or ''}".rstrip())
36
+
37
+ if b.console_truncated:
38
+ typer.echo(f"console: last {len(b.console)} of {b.console_lines} lines")
39
+
40
+ for line in b.console:
41
+ typer.echo(line)
42
+
43
+
44
+ @app.command("queue")
45
+ def queue() -> None:
46
+ """What waits in the build queue and why."""
47
+ for i in connect(options).queue():
48
+ typer.echo(f"{i.job}\t{i.since}\t{i.why or '-'}")