Skip to content

The Unified and Autonomous Development Platform

feat: Default project settings to be inherited by all root projects

Robin Shen15ff7edb625d
diff --git a/AGENTS.md b/AGENTS.md
index 8a9072630c..0c42e11add 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,6 +13,11 @@ files are generated automatically.
Do not add tests for trivial or minor changes unless the user explicitly asks
for them.
+Users may continue privileged work in an existing session after their
+privileges are revoked. Revoked privileges must be denied in a new session.
+Do not report continued access within the existing session as a security bug
+or require immediate revocation within that session.
+
For local development, start the OneDev server with `./dev.sh run` from the
repository root. The server can hot-load changed classes. Use `./dev.sh build`
to compile them; the first run performs a full compile, while subsequent runs
diff --git a/server-core/src/main/java/io/onedev/server/annotation/Editable.java b/server-core/src/main/java/io/onedev/server/annotation/Editable.java
index cdd257edc5..cd77172dc9 100644
--- a/server-core/src/main/java/io/onedev/server/annotation/Editable.java
+++ b/server-core/src/main/java/io/onedev/server/annotation/Editable.java
@@ -19,9 +19,9 @@ public @interface Editable {
String placeholderProvider() default "";
- String rootPlaceholder() default "";
+ String topPlaceholder() default "";
- String rootPlaceholderProvider() default "";
+ String topPlaceholderProvider() default "";
boolean displayPlaceholderAsValue() default false;
diff --git a/server-core/src/main/java/io/onedev/server/commandhandler/Translate.java b/server-core/src/main/java/io/onedev/server/commandhandler/Translate.java
index 6d37dd8966..92fbb40aa7 100644
--- a/server-core/src/main/java/io/onedev/server/commandhandler/Translate.java
+++ b/server-core/src/main/java/io/onedev/server/commandhandler/Translate.java
@@ -173,9 +173,9 @@ public class Translate extends CommandHandler {
if (placeholder.length() != 0) {
scannedTranslationKeys.add(placeholder);
}
- var rootPlaceholder = editable.rootPlaceholder();
- if (rootPlaceholder.length() != 0) {
- scannedTranslationKeys.add(rootPlaceholder);
+ var topPlaceholder = editable.topPlaceholder();
+ if (topPlaceholder.length() != 0) {
+ scannedTranslationKeys.add(topPlaceholder);
}
}
var notEmpty = method.getAnnotation(NotEmpty.class);
diff --git a/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java b/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java
index 6f9de6cdd0..6f9c015bc5 100644
--- a/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java
+++ b/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java
@@ -96,6 +96,7 @@ import io.onedev.server.model.EntityIdCounter;
import io.onedev.server.model.LinkSpec;
import io.onedev.server.model.ModelVersion;
import io.onedev.server.model.Project;
+import io.onedev.server.model.ProjectLastActivityDate;
import io.onedev.server.model.ProjectNumberCounter;
import io.onedev.server.model.Role;
import io.onedev.server.model.Setting;
@@ -710,6 +711,20 @@ public class DefaultDataService implements DataService, Serializable {
userService.replicate(unknown);
}
+ if (dao.get(Project.class, Project.DEFAULT_ID) == null) {
+ var lastActivityDate = new ProjectLastActivityDate();
+ dao.getSession().persist(lastActivityDate);
+ var defaultProject = new Project();
+ defaultProject.setId(Project.DEFAULT_ID);
+ defaultProject.setName("~default"); // Use an impossible name to avoid conflicts with actual projects
+ defaultProject.setPath("~default");
+ defaultProject.setLastActivityDate(lastActivityDate);
+ defaultProject = dao.getSession().merge(defaultProject);
+ var numberCounter = new ProjectNumberCounter();
+ numberCounter.setProject(defaultProject);
+ dao.getSession().persist(numberCounter);
+ }
+
// Initialize security setting first as initial password validation below relies on password policy
var setting = settingService.findSetting(Key.SECURITY);
if (setting == null) {
diff --git a/server-core/src/main/java/io/onedev/server/model/Project.java b/server-core/src/main/java/io/onedev/server/model/Project.java
index a14e90183b..d3c8b830ed 100644
--- a/server-core/src/main/java/io/onedev/server/model/Project.java
+++ b/server-core/src/main/java/io/onedev/server/model/Project.java
@@ -170,6 +170,10 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
private static final long serialVersionUID = 1L;
+ public static final Long DEFAULT_ID = -1L;
+
+ public static final String DEFAULT_NAME = "~default";
+
public static final String BUILDS_DIR = "builds";
public static final String ATTACHMENT_DIR = "attachment";
@@ -563,8 +567,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
public List<BranchProtection> getHierarchyBranchProtections() {
List<BranchProtection> branchProtections = new ArrayList<>(getBranchProtections());
- if (getParent() != null)
- branchProtections.addAll(getParent().getHierarchyBranchProtections());
+ if (getSettingsParent() != null)
+ branchProtections.addAll(getSettingsParent().getHierarchyBranchProtections());
return branchProtections;
}
@@ -578,8 +582,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
public List<TagProtection> getHierarchyTagProtections() {
List<TagProtection> tagProtections = new ArrayList<>(getTagProtections());
- if (getParent() != null)
- tagProtections.addAll(getParent().getHierarchyTagProtections());
+ if (getSettingsParent() != null)
+ tagProtections.addAll(getSettingsParent().getHierarchyTagProtections());
return tagProtections;
}
@@ -720,6 +724,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
}
public List<RefFacade> getCommitRefs(String prefix) {
+ if (DEFAULT_ID.equals(getId()))
+ return new ArrayList<>();
return getGitService().getCommitRefs(this, prefix);
}
@@ -783,6 +789,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
@Nullable
public String getDefaultBranch() {
+ if (DEFAULT_ID.equals(getId()))
+ return null;
if (defaultBranch == null)
defaultBranch = Optional.fromNullable(getGitService().getDefaultBranch(this));
return defaultBranch.orNull();
@@ -1132,8 +1140,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
var specMap = new LinkedHashMap<String, WorkspaceSpec>();
for (var spec : getWorkspaceSpecs())
specMap.put(spec.getName(), spec);
- if (getParent() != null) {
- for (var spec : getParent().getHierarchyWorkspaceSpecs())
+ if (getSettingsParent() != null) {
+ for (var spec : getSettingsParent().getHierarchyWorkspaceSpecs())
specMap.putIfAbsent(spec.getName(), spec);
}
hierarchyWorkspaceSpecs = new ArrayList<>(specMap.values());
@@ -1155,6 +1163,24 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
this.serviceDeskEmailAddress = serviceDeskEmailAddress;
}
+ /**
+ * The next project to consult for inheritable settings, without changing the project tree.
+ */
+ @Nullable
+ public Project getSettingsParent() {
+ if (getParent() != null)
+ return getParent();
+ else if (!DEFAULT_ID.equals(getId()) && WicketUtils.isSubscriptionActive())
+ return getProjectService().load(DEFAULT_ID);
+ else
+ return null;
+ }
+
+ public boolean isSelfOrSettingsAncestorOf(Project project) {
+ return DEFAULT_ID.equals(getId()) && WicketUtils.isSubscriptionActive()
+ || isSelfOrAncestorOf(project);
+ }
+
public GitPackConfig getGitPackConfig() {
return gitPackConfig;
}
@@ -1174,7 +1200,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
}
public WikiFolder getWikiFolder() {
- for (Project current = this; current != null; current = current.getParent()) {
+ for (Project current = this; current != null; current = current.getSettingsParent()) {
if (current.getWikiSetting().getFolder() != null)
return current.getWikiSetting().getFolder();
}
@@ -1231,16 +1257,16 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
public List<JobSecret> getHierarchyJobSecrets() {
List<JobSecret> jobSecrets = new ArrayList<>(getBuildSetting().getJobSecrets());
- if (getParent() != null)
- jobSecrets.addAll(getParent().getHierarchyJobSecrets());
+ if (getSettingsParent() != null)
+ jobSecrets.addAll(getSettingsParent().getHierarchyJobSecrets());
return jobSecrets;
}
public List<JobProperty> getHierarchyJobProperties() {
List<JobProperty> jobProperties = new ArrayList<>(getBuildSetting().getJobProperties());
- if (getParent() != null) {
+ if (getSettingsParent() != null) {
Set<String> names = jobProperties.stream().map(it->it.getName()).collect(Collectors.toSet());
- for (JobProperty jobProperty : getParent().getHierarchyJobProperties()) {
+ for (JobProperty jobProperty : getSettingsParent().getHierarchyJobProperties()) {
if (!names.contains(jobProperty.getName()))
jobProperties.add(jobProperty);
}
@@ -1250,15 +1276,15 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
public List<DefaultFixedIssueFilter> getHierarchyDefaultFixedIssueFilters() {
List<DefaultFixedIssueFilter> defaultFixedIssueFilters = new ArrayList<>(getBuildSetting().getDefaultFixedIssueFilters());
- if (getParent() != null)
- defaultFixedIssueFilters.addAll(getParent().getHierarchyDefaultFixedIssueFilters());
+ if (getSettingsParent() != null)
+ defaultFixedIssueFilters.addAll(getSettingsParent().getHierarchyDefaultFixedIssueFilters());
return defaultFixedIssueFilters;
}
public List<BuildPreservation> getHierarchyBuildPreservations() {
List<BuildPreservation> buildPreservations = new ArrayList<>(getBuildSetting().getBuildPreservations());
- if (getParent() != null)
- buildPreservations.addAll(getParent().getHierarchyBuildPreservations());
+ if (getSettingsParent() != null)
+ buildPreservations.addAll(getSettingsParent().getHierarchyBuildPreservations());
return buildPreservations;
}
@@ -1276,8 +1302,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
var cachePreserveDays = getBuildSetting().getCachePreserveDays();
if (cachePreserveDays != null)
return cachePreserveDays;
- else if (getParent() != null)
- return getParent().getHierarchyCachePreserveDays();
+ else if (getSettingsParent() != null)
+ return getSettingsParent().getHierarchyCachePreserveDays();
else
return ProjectBuildSetting.DEFAULT_CACHE_PRESERVE_DAYS;
}
@@ -1456,8 +1482,8 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
public List<WebHook> getHierarchyWebHooks() {
List<WebHook> webHooks = new ArrayList<>(getWebHooks());
- if (getParent() != null)
- webHooks.addAll(getParent().getHierarchyWebHooks());
+ if (getSettingsParent() != null)
+ webHooks.addAll(getSettingsParent().getHierarchyWebHooks());
return webHooks;
}
@@ -2103,7 +2129,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
do {
if (current.getAiSetting().getExcludedReviewFiles() != null)
return current.getAiSetting().getExcludedReviewFiles();
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return null;
@@ -2114,7 +2140,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
do {
if (current.getCodeIndexingSetting().getAnalyzeFiles() != null)
return current.getCodeIndexingSetting().getAnalyzeFiles();
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return "**";
@@ -2125,7 +2151,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
do {
if (current.getCodeIndexingSetting().getRequireLoginForAutoIndexing() != null)
return current.getCodeIndexingSetting().getRequireLoginForAutoIndexing();
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return false;
@@ -2137,7 +2163,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
do {
if (current.getIssueSetting().getBranchPrefix() != null)
return current.getIssueSetting().getBranchPrefix();
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return null;
@@ -2148,7 +2174,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
do {
if (current.getPullRequestSetting().getDefaultMergeStrategy() != null)
return current.getPullRequestSetting().getDefaultMergeStrategy();
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return MergeStrategy.CREATE_MERGE_COMMIT;
@@ -2159,7 +2185,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
do {
if (current.getPullRequestSetting().getDeleteSourceBranchAfterMerge() != null)
return current.getPullRequestSetting().getDeleteSourceBranchAfterMerge();
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return false;
@@ -2180,7 +2206,7 @@ public class Project extends AbstractEntity implements LabelSupport<ProjectLabel
}
return users;
}
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
return new ArrayList<>();
diff --git a/server-core/src/main/java/io/onedev/server/model/support/CodeIndexingSetting.java b/server-core/src/main/java/io/onedev/server/model/support/CodeIndexingSetting.java
index bd5c285822..b6db25ffae 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/CodeIndexingSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/CodeIndexingSetting.java
@@ -18,7 +18,7 @@ public class CodeIndexingSetting implements Serializable {
@Api(description = "Leave empty to inherit from parent project, or false if no parent")
private Boolean requireLoginForAutoIndexing;
- @Editable(order=100, name="Files to Be Indexed", placeholder="Inherit from parent", rootPlaceholder ="All files", description="""
+ @Editable(order=100, name="Files to Be Indexed", placeholder="Inherit from parent", topPlaceholder ="All files", description="""
Specify which repository files OneDev should index. During indexing, OneDev analyzes these files for code search, line statistics, and code contribution statistics.
<b>NOTE: </b> Changing this setting only affects new commits. To apply the change to history commits, please stop the server and delete folder
<code>index</code> and <code>info/commit</code> under <a href='https://docs.onedev.io/concepts#project-storage' target='_blank'>project's storage directory</a>.
@@ -33,7 +33,7 @@ public class CodeIndexingSetting implements Serializable {
this.analysisFiles = analyzeFiles;
}
- @Editable(order=200, name="Require Login for Automatic Indexing", placeholder="Inherit from parent", rootPlaceholder="No", description="""
+ @Editable(order=200, name="Require Login for Automatic Indexing", placeholder="Inherit from parent", topPlaceholder="No", description="""
If enabled, a login session is required to automatically trigger code indexing when browsing repository files or viewing diffs.
This is useful for public projects to prevent anonymous AI crawlers from triggering indexing of every historical commit and generating a huge index cache.""")
@Nullable
diff --git a/server-core/src/main/java/io/onedev/server/model/support/ProjectAiSetting.java b/server-core/src/main/java/io/onedev/server/model/support/ProjectAiSetting.java
index 36c30dffa6..ebbacf3735 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/ProjectAiSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/ProjectAiSetting.java
@@ -14,7 +14,7 @@ public class ProjectAiSetting implements Serializable {
private String excludedReviewFiles;
- @Editable(order=100, name="Excluded Files for Review", placeholder="Inherit from parent", rootPlaceholder="No excluded files", description="""
+ @Editable(order=100, name="Excluded Files for Review", placeholder="Inherit from parent", topPlaceholder="No excluded files", description="""
Optionally specify files to be excluded when reviewing code with AI user to save tokens""")
@Patterns(path=true)
@Nullable
diff --git a/server-core/src/main/java/io/onedev/server/model/support/WebHook.java b/server-core/src/main/java/io/onedev/server/model/support/WebHook.java
index a5ad39f28d..89df126cdf 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/WebHook.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/WebHook.java
@@ -10,8 +10,9 @@ import io.onedev.server.event.project.workspace.WorkspaceEvent;
import io.onedev.server.util.CryptoUtils;
import io.onedev.server.annotation.Editable;
+import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
-import jakarta.validation.constraints.Size;
+import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@@ -101,8 +102,8 @@ public class WebHook implements Serializable {
}
@Editable(order=200)
- @Size(min=1, message="At least one event type needs to be selected")
- public List<EventType> getEventTypes() {
+ @NotEmpty(message="At least one event type needs to be selected")
+ public List<@NotNull EventType> getEventTypes() {
return eventTypes;
}
@@ -123,7 +124,8 @@ public class WebHook implements Serializable {
@Editable(order=400, name="Custom Headers", description="Optionally specify additional HTTP headers to include in "
+ "the webhook POST request, for example an Authorization header required by the receiving endpoint")
- public List<WebHookHeader> getHeaders() {
+ @NotNull
+ public List<@NotNull @Valid WebHookHeader> getHeaders() {
return headers;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/code/BranchProtection.java b/server-core/src/main/java/io/onedev/server/model/support/code/BranchProtection.java
index c1436b39e1..b78a6db6eb 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/code/BranchProtection.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/code/BranchProtection.java
@@ -14,6 +14,7 @@ import java.util.stream.Collectors;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.NotNull;
import org.eclipse.jgit.lib.ObjectId;
import org.jspecify.annotations.Nullable;
@@ -192,7 +193,8 @@ public class BranchProtection implements Serializable {
}
@Editable(order=410, placeholder = "No disallowed file types", description = "Optionally specify disallowed file types by extensions (hit ENTER to add value), for instance <code>exe</code>, <code>bin</code>. Leave empty to allow all file types")
- public List<String> getDisallowedFileTypes() {
+ @NotNull
+ public List<@NotNull String> getDisallowedFileTypes() {
return disallowedFileTypes;
}
@@ -203,7 +205,8 @@ public class BranchProtection implements Serializable {
@Editable(order=500, name="Required Builds", placeholder="No any", description="Optionally choose required builds. You may also " +
"input jobs not listed here, and press ENTER to add them")
@JobChoice(tagsMode=true)
- public List<String> getJobNames() {
+ @NotNull
+ public List<@NotNull String> getJobNames() {
return jobNames;
}
@@ -212,7 +215,8 @@ public class BranchProtection implements Serializable {
}
@Editable(order=700, description="Optionally specify path protection rules")
- public List<@Valid FileProtection> getFileProtections() {
+ @NotNull
+ public List<@NotNull @Valid FileProtection> getFileProtections() {
return fileProtections;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/code/FileProtection.java b/server-core/src/main/java/io/onedev/server/model/support/code/FileProtection.java
index 0ee37dd168..ee8fa10b2a 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/code/FileProtection.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/code/FileProtection.java
@@ -46,8 +46,9 @@ public class FileProtection implements Serializable, Validatable {
@SuppressWarnings("unused")
private static List<InputSuggestion> suggestPaths(String matchWith) {
- if (Project.get() != null)
- return SuggestionUtils.suggestBlobs(Project.get(), matchWith);
+ var project = Project.get();
+ if (project != null && !Project.DEFAULT_ID.equals(project.getId()))
+ return SuggestionUtils.suggestBlobs(project, matchWith);
else
return new ArrayList<>();
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/issue/ProjectIssueSetting.java b/server-core/src/main/java/io/onedev/server/model/support/issue/ProjectIssueSetting.java
index 8dfd5c47fc..33bf570e24 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/issue/ProjectIssueSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/issue/ProjectIssueSetting.java
@@ -110,7 +110,7 @@ public class ProjectIssueSetting implements Serializable {
this.transitionSpecs = transitionSpecs;
}
- @Editable(name="Branch Prefix", placeholder="Inherit from parent", rootPlaceholder="No prefix", description="""
+ @Editable(name="Branch Prefix", placeholder="Inherit from parent", topPlaceholder="No prefix", description="""
Optionally specify a prefix to be prepended (as a path segment) when generate issue branch.
For instance with prefix <code>feature</code>, generated issue branch will be
<code>feature/issue-100-some-title</code>""")
diff --git a/server-core/src/main/java/io/onedev/server/model/support/pullrequest/ProjectPullRequestSetting.java b/server-core/src/main/java/io/onedev/server/model/support/pullrequest/ProjectPullRequestSetting.java
index e15a8de3c7..16fa59c036 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/pullrequest/ProjectPullRequestSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/pullrequest/ProjectPullRequestSetting.java
@@ -52,7 +52,7 @@ public class ProjectPullRequestSetting implements Serializable {
}
}
- @Editable(order=200, placeholder = "Inherit from parent", rootPlaceholder = "Create merge commit",
+ @Editable(order=200, placeholder = "Inherit from parent", topPlaceholder = "Create merge commit",
description = "Specify default merge strategy of pull requests submitted to this project")
public MergeStrategy getDefaultMergeStrategy() {
return defaultMergeStrategy;
@@ -62,7 +62,7 @@ public class ProjectPullRequestSetting implements Serializable {
this.defaultMergeStrategy = defaultMergeStrategy;
}
- @Editable(order=300, placeholder = "Inherit from parent", rootPlaceholder = "Not assigned", description = "" +
+ @Editable(order=300, placeholder = "Inherit from parent", topPlaceholder = "Not assigned", description = "" +
"Specify default assignees of pull requests submitted to this project. " +
"Only users with the write code permission to the project can be selected")
@UserChoice("getAssigneeChoices")
@@ -81,7 +81,7 @@ public class ProjectPullRequestSetting implements Serializable {
return choices;
}
- @Editable(order=400, placeholder = "Inherit from parent", rootPlaceholder = "No", description = "" +
+ @Editable(order=400, placeholder = "Inherit from parent", topPlaceholder = "No", description = "" +
"If enabled, source branch will be deleted automatically after merge the pull request if " +
"user has permission to do that")
public Boolean getDeleteSourceBranchAfterMerge() {
diff --git a/server-core/src/main/java/io/onedev/server/model/support/wiki/WikiSetting.java b/server-core/src/main/java/io/onedev/server/model/support/wiki/WikiSetting.java
index 655cc4171b..8419ae2ee5 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/wiki/WikiSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/wiki/WikiSetting.java
@@ -12,8 +12,8 @@ public class WikiSetting implements Serializable {
private static final long serialVersionUID = 1L;
private WikiFolder folder;
- @Editable(name="Wiki Folder", placeholder="Inherit from parent", rootPlaceholder="Use folder 'wiki'", description="""
- Specify the repository folder to store wiki pages. Leave empty to inherit from parent.
+ @Editable(name="Wiki Folder", placeholder="Inherit from parent", topPlaceholder="Use folder 'wiki'", description="""
+ Specify the repository folder to store wiki pages.
If you do not want to store wiki pages in the project repository, the specified folder
can be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>
file in the wiki root folder with Git ignore patterns relative to that folder""")
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java
index e29719166f..3256846e84 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java
@@ -8,6 +8,7 @@ import java.util.List;
import java.util.stream.Collectors;
import jakarta.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.NotNull;
import io.onedev.server.OneDev;
import io.onedev.server.annotation.Editable;
@@ -46,7 +47,8 @@ public class TaskAutomation implements Serializable {
Optionally specify applicable AI users to use this workspace spec for task automation. Leave empty to allow all AI users.
When a AI user creates workspace to do its job, the first applicable spec will be used.""")
@UserChoice("getAiUsers")
- public List<String> getApplicableAis() {
+ @NotNull
+ public List<@NotNull String> getApplicableAis() {
return applicableAis;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java
index 68287e20d3..767d35852c 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java
@@ -105,9 +105,9 @@ public class WorkspaceSpec implements Serializable, Validatable {
@SuppressWarnings("unused")
private static List<InputCompletion> getNameSuggestions(InputStatus status) {
Project project = Project.get();
- if (project != null && project.getParent() != null) {
+ if (project != null && project.getSettingsParent() != null) {
List<String> candidates = new ArrayList<>();
- for (var spec : project.getParent().getHierarchyWorkspaceSpecs())
+ for (var spec : project.getSettingsParent().getHierarchyWorkspaceSpecs())
candidates.add(spec.getName());
project.getWorkspaceSpecs().forEach(it -> candidates.remove(it.getName()));
return SuggestionUtils.suggestOverrides(candidates, status);
@@ -179,6 +179,7 @@ public class WorkspaceSpec implements Serializable, Validatable {
@Editable(order = 300, description = """
Configure shell of the workspace. It will be used to launch workspace terminal, run workspace setup commands etc
""")
+ @Valid
@NotNull
public WorkspaceShell getShell() {
return shell;
@@ -204,7 +205,8 @@ public class WorkspaceSpec implements Serializable, Validatable {
Optionally specify container ports to expose. These ports will be mapped to random ports on host
which will be displayed on the workspace page""")
@DependsOn(property = "runInContainer")
- public List<Integer> getContainerPorts() {
+ @NotNull
+ public List<@NotNull Integer> getContainerPorts() {
return containerPorts;
}
@@ -213,7 +215,8 @@ public class WorkspaceSpec implements Serializable, Validatable {
}
@Editable(order = 400, name = "Environment Variables", description = "Optionally specify environment variables")
- public List<@Valid EnvVar> getEnvVars() {
+ @NotNull
+ public List<@NotNull @Valid EnvVar> getEnvVars() {
return envVars;
}
@@ -224,7 +227,8 @@ public class WorkspaceSpec implements Serializable, Validatable {
@Editable(order = 600, name = "Shortcuts", description = """
Optionally specify list of shortcuts at top of workspace. When workspace is created,
the first shortcut will be opened automatically""")
- public List<@Valid ShortcutConfig> getShortcutConfigs() {
+ @NotNull
+ public List<@NotNull @Valid ShortcutConfig> getShortcutConfigs() {
return shortcutConfigs;
}
@@ -284,7 +288,8 @@ public class WorkspaceSpec implements Serializable, Validatable {
<code>@workspace_token@</code> for user name, and access token for password
""")
@DependsOn(property = "runInContainer")
- public List<@Valid RegistryLogin> getRegistryLogins() {
+ @NotNull
+ public List<@NotNull @Valid RegistryLogin> getRegistryLogins() {
return registryLogins;
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java
index 97e8ed3bdf..de2054412b 100644
--- a/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java
@@ -153,7 +153,7 @@ public abstract class ChannelNotificationManager<T extends ChannelNotificationSe
T setting = project.getContributedSetting(settingClass);
for (var notification : setting.getNotifications())
notifications.putIfAbsent(notification.getWebhookUrl(), notification);
- project = project.getParent();
+ project = project.getSettingsParent();
} while (project != null);
return notifications.values();
diff --git a/server-core/src/main/java/io/onedev/server/rest/RestProjectUtils.java b/server-core/src/main/java/io/onedev/server/rest/RestProjectUtils.java
new file mode 100644
index 0000000000..155d3564b1
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/RestProjectUtils.java
@@ -0,0 +1,41 @@
+package io.onedev.server.rest;
+
+import jakarta.ws.rs.NotFoundException;
+
+import org.apache.shiro.authz.UnauthorizedException;
+
+import io.onedev.server.exception.NoSubscriptionException;
+import io.onedev.server.model.Project;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.web.util.WicketUtils;
+
+public class RestProjectUtils {
+
+ public static void checkProjectId(Long projectId) {
+ if (projectId != null && projectId < 0)
+ throw new NotFoundException("Project not found");
+ }
+
+ public static Project loadProject(ProjectService projectService, Long projectId) {
+ checkProjectId(projectId);
+ return projectService.load(projectId);
+ }
+
+ public static void checkProjectDefaultsPermission() {
+ if (!SecurityUtils.isAdministrator())
+ throw new UnauthorizedException();
+ if (!WicketUtils.isSubscriptionActive())
+ throw new NoSubscriptionException("Project defaults");
+ }
+
+ public static void checkAuthorizationPermission(Project project) {
+ if (Project.DEFAULT_ID.equals(project.getId())) {
+ checkProjectDefaultsPermission();
+ } else {
+ checkProjectId(project.getId());
+ if (!SecurityUtils.canManageProject(project))
+ throw new UnauthorizedException();
+ }
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java
index 660ca785df..6a0a1b56af 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java
@@ -4,6 +4,19 @@ import static io.onedev.server.security.SecurityUtils.canManageProject;
import static io.onedev.server.security.SecurityUtils.getAuthUser;
import static io.onedev.server.security.SecurityUtils.isAdministrator;
+import java.util.function.Function;
+
+import org.apache.shiro.authz.UnauthorizedException;
+
+import io.onedev.server.data.migration.VersionedXmlDoc;
+import io.onedev.server.exception.NotAcceptableException;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.User;
+import io.onedev.server.rest.RestProjectUtils;
+import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.service.AccessTokenAuthorizationService;
+import io.onedev.server.service.AuditService;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import jakarta.validation.constraints.NotNull;
@@ -18,14 +31,6 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
-import org.apache.shiro.authz.UnauthorizedException;
-
-import io.onedev.server.data.migration.VersionedXmlDoc;
-import io.onedev.server.service.AccessTokenAuthorizationService;
-import io.onedev.server.service.AuditService;
-import io.onedev.server.model.AccessTokenAuthorization;
-import io.onedev.server.rest.annotation.Api;
-
@Api(description = "This resource manages project authorizations of access tokens. Note that " +
"project authorizations will not take effect if option <tt>hasOwnerPermissions</tt> is enabled " +
"for associated access token")
@@ -60,10 +65,7 @@ public class AccessTokenAuthorizationResource {
@POST
public Long createAuthorization(@NotNull AccessTokenAuthorization authorization) {
var owner = authorization.getToken().getOwner();
- if (!isAdministrator() && !owner.equals(getAuthUser()))
- throw new UnauthorizedException();
- if (!canManageProject(owner.asSubject(), authorization.getProject()))
- throw new BadRequestException("Access token owner should have permission to manage authorized project");
+ checkAuthorization(owner, authorization.getProject(), BadRequestException::new);
accessTokenAuthorizationService.createOrUpdate(authorization);
if (!getAuthUser().equals(owner)) {
@@ -78,10 +80,7 @@ public class AccessTokenAuthorizationResource {
@POST
public Response updateAuthorization(@PathParam("authorizationId") Long authorizationId, @NotNull AccessTokenAuthorization authorization) {
var owner = authorization.getToken().getOwner();
- if (!isAdministrator() && !owner.equals(getAuthUser()))
- throw new UnauthorizedException();
- if (!canManageProject(owner.asSubject(), authorization.getProject()))
- throw new BadRequestException("Access token owner should have permission to manage authorized project");
+ checkAuthorization(owner, authorization.getProject(), NotAcceptableException::new);
accessTokenAuthorizationService.createOrUpdate(authorization);
if (!getAuthUser().equals(owner)) {
@@ -91,6 +90,21 @@ public class AccessTokenAuthorizationResource {
}
return Response.ok().build();
}
+
+ private void checkAuthorization(User owner, Project project, Function<String, RuntimeException> invalidOwner) {
+ if (!isAdministrator() && !owner.equals(getAuthUser()))
+ throw new UnauthorizedException();
+ var ownerSubject = owner.asSubject();
+ if (Project.DEFAULT_ID.equals(project.getId())) {
+ RestProjectUtils.checkProjectDefaultsPermission();
+ if (!isAdministrator(ownerSubject))
+ throw invalidOwner.apply("Access token owner should be an administrator to authorize project defaults");
+ } else {
+ RestProjectUtils.checkProjectId(project.getId());
+ }
+ if (!canManageProject(ownerSubject, project))
+ throw invalidOwner.apply("Access token owner should have permission to manage authorized project");
+ }
@Api(order=300, description = "Delete access token authorization of specified id")
@Path("/{authorizationId}")
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/BaseAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/BaseAuthorizationResource.java
index c30f3011bb..b6e5c6092b 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/BaseAuthorizationResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/BaseAuthorizationResource.java
@@ -13,14 +13,12 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
-import org.apache.shiro.authz.UnauthorizedException;
-
import io.onedev.server.data.migration.VersionedXmlDoc;
import io.onedev.server.service.AuditService;
import io.onedev.server.service.BaseAuthorizationService;
import io.onedev.server.model.BaseAuthorization;
import io.onedev.server.rest.annotation.Api;
-import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.rest.RestProjectUtils;
@Api(description = "This resource manages default roles of project")
@Path("/base-authorizations")
@@ -44,16 +42,14 @@ public class BaseAuthorizationResource {
@GET
public BaseAuthorization getAuthorization(@PathParam("authorizationId") Long authorizationId) {
var authorization = authorizationService.load(authorizationId);
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
return authorization;
}
@Api(order=200, description="Create base authorization")
@POST
public Long createAuthorization(@NotNull BaseAuthorization authorization) {
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
authorizationService.create(authorization);
var newAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(authorization.getProject(), "created base authorization via RESTful API", null, newAuditContent);
@@ -65,8 +61,7 @@ public class BaseAuthorizationResource {
@DELETE
public Response deleteAuthorization(@PathParam("authorizationId") Long authorizationId) {
var authorization = authorizationService.load(authorizationId);
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
authorizationService.delete(authorization);
var oldAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(authorization.getProject(), "deleted base authorization via RESTful API", oldAuditContent, null);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java
index 0f59bb2f06..b40ee108fc 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java
@@ -45,6 +45,7 @@ import io.onedev.server.model.CodeCommentStatusChange;
import io.onedev.server.model.Project;
import io.onedev.server.model.support.CompareContext;
import io.onedev.server.model.support.Mark;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -139,7 +140,7 @@ public class CodeCommentResource {
@QueryParam("query") @Api(description="Syntax of this query is the same as in the project's code comments page", example="unresolved") String query,
@QueryParam("offset") @Api(example="0") int offset,
@QueryParam("count") @Api(example="100") int count) {
- var project = projectService.load(projectId);
+ var project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project))
throw new UnauthorizedException();
var subject = SecurityUtils.getSubject();
@@ -155,7 +156,7 @@ public class CodeCommentResource {
var user = SecurityUtils.getUser();
if (user == null)
throw new UnauthenticatedException();
- var project = projectService.load(data.getProjectId());
+ var project = RestProjectUtils.loadProject(projectService, data.getProjectId());
if (!SecurityUtils.canReadCode(project))
throw new UnauthorizedException();
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/GroupAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/GroupAuthorizationResource.java
index 16f39f0284..b79958602f 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/GroupAuthorizationResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/GroupAuthorizationResource.java
@@ -13,14 +13,12 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
-import org.apache.shiro.authz.UnauthorizedException;
-
import io.onedev.server.data.migration.VersionedXmlDoc;
import io.onedev.server.service.AuditService;
import io.onedev.server.service.GroupAuthorizationService;
import io.onedev.server.model.GroupAuthorization;
import io.onedev.server.rest.annotation.Api;
-import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.rest.RestProjectUtils;
@Path("/group-authorizations")
@Consumes(MediaType.APPLICATION_JSON)
@@ -43,16 +41,14 @@ public class GroupAuthorizationResource {
@GET
public GroupAuthorization getAuthorization(@PathParam("authorizationId") Long authorizationId) {
var authorization = authorizationService.load(authorizationId);
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
return authorization;
}
@Api(order=200, description="Create new group authorization")
@POST
public Long createAuthorization(@NotNull GroupAuthorization authorization) {
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
authorizationService.createOrUpdate(authorization);
var newAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(authorization.getProject(), "created group authorization via RESTful API", null, newAuditContent);
@@ -64,8 +60,7 @@ public class GroupAuthorizationResource {
@DELETE
public Response deleteAuthorization(@PathParam("authorizationId") Long authorizationId) {
var authorization = authorizationService.load(authorizationId);
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
authorizationService.delete(authorization);
var oldAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(authorization.getProject(), "deleted group authorization via RESTful API", oldAuditContent, null);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java
index 13d5a8fe5e..c0368def74 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java
@@ -53,6 +53,7 @@ import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.support.issue.field.FieldUtils;
import io.onedev.server.model.support.issue.transitionspec.ManualSpec;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -321,7 +322,7 @@ public class IssueResource {
var subject = SecurityUtils.getSubject();
var user = SecurityUtils.getUser(subject);
- Project project = projectService.load(data.getProjectId());
+ Project project = RestProjectUtils.loadProject(projectService, data.getProjectId());
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/JobRunResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/JobRunResource.java
index 90c17f0f71..f43b514eff 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/JobRunResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/JobRunResource.java
@@ -9,6 +9,7 @@ import io.onedev.server.model.Build;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.support.pullrequest.MergePreview;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.JobRun;
import io.onedev.server.rest.resource.support.JobRunOnCommit;
@@ -70,7 +71,7 @@ public class JobRunResource {
if (jobRun instanceof JobRunOnCommit) {
JobRunOnCommit jobRunOnCommit = (JobRunOnCommit) jobRun;
- project = projectService.load(jobRunOnCommit.getProjectId());
+ project = RestProjectUtils.loadProject(projectService, jobRunOnCommit.getProjectId());
if (!SecurityUtils.canRunJob(subject, project, jobRun.getJobName()))
throw new UnauthorizedException();
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/PackBlobResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/PackBlobResource.java
index 11dca41a81..c081034655 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/PackBlobResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/PackBlobResource.java
@@ -17,6 +17,7 @@ import org.apache.shiro.authz.UnauthorizedException;
import io.onedev.server.service.PackBlobService;
import io.onedev.server.model.PackBlob;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.security.SecurityUtils;
@@ -37,6 +38,7 @@ public class PackBlobResource {
@Api(order=100, description = "Find package blob by project id and hash")
@GET
public PackBlob findByHash(@QueryParam("projectId") Long projectId, @QueryParam("hash") String hash) {
+ RestProjectUtils.checkProjectId(projectId);
var packBlob = packBlobService.findBySha256Hash(projectId, hash);
if (packBlob != null)
return packBlob;
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java
index 7962367da5..f6eb81d191 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java
@@ -64,6 +64,7 @@ import io.onedev.server.model.support.pullrequest.ProjectPullRequestSetting;
import io.onedev.server.model.support.wiki.WikiSetting;
import io.onedev.server.model.support.workspace.ProjectWorkspaceSetting;
import io.onedev.server.persistence.dao.EntityCriteria;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -105,7 +106,7 @@ public class ProjectResource {
@Path("/{projectId}")
@GET
public ProjectData getProject(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
return ProjectData.from(project);
@@ -117,6 +118,7 @@ public class ProjectResource {
public Long getProjectId(@PathParam("path") String path) {
var project = projectService.findByPath(path);
if (project != null) {
+ RestProjectUtils.checkProjectId(project.getId());
if (!SecurityUtils.canAccessProject(project))
throw new NotFoundException("Project not found or inaccessible: " + path);
return project.getId();
@@ -129,7 +131,7 @@ public class ProjectResource {
@Path("/{projectId}/clone-url")
@GET
public CloneUrl getCloneURL(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
@@ -144,7 +146,7 @@ public class ProjectResource {
@Path("/{projectId}/setting")
@GET
public ProjectSetting getSetting(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canManageProject(project))
throw new UnauthorizedException();
return ProjectSetting.from(project);
@@ -154,7 +156,7 @@ public class ProjectResource {
@Path("/{projectId}/forks")
@GET
public Collection<ProjectData> getForks(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
return project.getForks().stream().map(ProjectData::from).collect(Collectors.toList());
@@ -164,7 +166,7 @@ public class ProjectResource {
@Path("/{projectId}/base-authorizations")
@GET
public Collection<BaseAuthorization> getBaseAuthorizations(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canManageProject(project))
throw new UnauthorizedException();
return project.getBaseAuthorizations();
@@ -174,7 +176,7 @@ public class ProjectResource {
@Path("/{projectId}/group-authorizations")
@GET
public Collection<GroupAuthorization> getGroupAuthorizations(@PathParam("projectId") Long projectId) {
- var project = projectService.load(projectId);
+ var project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canManageProject(project))
throw new UnauthorizedException();
return project.getGroupAuthorizations();
@@ -184,7 +186,7 @@ public class ProjectResource {
@Path("/{projectId}/user-authorizations")
@GET
public Collection<UserAuthorization> getUserAuthorizations(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canManageProject(project))
throw new UnauthorizedException();
return project.getUserAuthorizations();
@@ -194,7 +196,7 @@ public class ProjectResource {
@Path("/{projectId}/labels")
@GET
public Collection<ProjectLabel> getLabels(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
return project.getLabels();
@@ -228,7 +230,7 @@ public class ProjectResource {
@QueryParam("dueAfter") @Api(exampleProvider="getDateExample", description="ISO 8601 date") String dueAfter,
@QueryParam("closed") Boolean closed, @QueryParam("offset") @Api(example="0") int offset,
@QueryParam("count") @Api(example="100") int count) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
@@ -260,7 +262,7 @@ public class ProjectResource {
@QueryParam("sinceDate") @NotEmpty @Api(description="Since date of format <i>yyyy-MM-dd</i>") String since,
@QueryParam("untilDate") @NotEmpty @Api(description="Until date of format <i>yyyy-MM-dd</i>") String until,
@QueryParam("count") int count) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canAccessProject(project))
throw new UnauthorizedException();
@@ -325,7 +327,7 @@ public class ProjectResource {
@Path("/{projectId}")
@POST
public Response updateProject(@PathParam("projectId") Long projectId, @NotNull @Valid ProjectData data) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
var subject = SecurityUtils.getSubject();
if (!SecurityUtils.canManageProject(subject, project))
@@ -336,7 +338,7 @@ public class ProjectResource {
data.populate(project, projectService);
- Project parent = data.getParentId() != null? projectService.load(data.getParentId()) : null;
+ Project parent = data.getParentId() != null? RestProjectUtils.loadProject(projectService, data.getParentId()) : null;
if (!Objects.equals(oldParentId, Project.idOf(parent)))
checkProjectCreationPermission(subject, parent);
@@ -377,6 +379,9 @@ public class ProjectResource {
@Path("/{projectId}/setting")
@POST
public Response updateSetting(@PathParam("projectId") Long projectId, @NotNull ProjectSetting setting) {
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
+ if (!SecurityUtils.canManageProject(project))
+ throw new UnauthorizedException();
var boardSpecs = setting.getIssueSetting().getBoardSpecs();
if (boardSpecs != null) {
for (var boardSpec: boardSpecs)
@@ -388,9 +393,6 @@ public class ProjectResource {
throw new ExplicitException(violation.getPropertyPath() + ": " + violation.getMessage());
}
- Project project = projectService.load(projectId);
- if (!SecurityUtils.canManageProject(project))
- throw new UnauthorizedException();
var oldAuditContent = VersionedXmlDoc.fromBean(ProjectSetting.from(project)).toXML();
setting.populate(project);
projectService.update(project);
@@ -403,7 +405,7 @@ public class ProjectResource {
@Path("/{projectId}")
@DELETE
public Response deleteProject(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canManageProject(project))
throw new UnauthorizedException();
projectService.delete(project);
@@ -630,12 +632,14 @@ public class ProjectResource {
}
public void populate(Project project, ProjectService projectService) {
+ RestProjectUtils.checkProjectId(parentId);
+ RestProjectUtils.checkProjectId(forkedFromId);
if (parentId != null)
- project.setParent(projectService.load(getParentId()));
+ project.setParent(RestProjectUtils.loadProject(projectService, getParentId()));
else
project.setParent(null);
if (forkedFromId != null)
- project.setForkedFrom(projectService.load(getForkedFromId()));
+ project.setForkedFrom(RestProjectUtils.loadProject(projectService, getForkedFromId()));
else
project.setForkedFrom(null);
project.setName(getName());
@@ -824,21 +828,24 @@ public class ProjectResource {
project.setContributedSettings(contributedSettings);
}
+ protected void populateFrom(Project project) {
+ setBranchProtections(project.getBranchProtections());
+ setTagProtections(project.getTagProtections());
+ setBuildSetting(project.getBuildSetting());
+ setPackSetting(project.getPackSetting());
+ setIssueSetting(project.getIssueSetting());
+ setWikiSetting(project.getWikiSetting());
+ setNamedCodeCommentQueries(project.getNamedCodeCommentQueries());
+ setNamedCommitQueries(project.getNamedCommitQueries());
+ setPullRequestSetting(project.getPullRequestSetting());
+ setWorkspaceSetting(project.getWorkspaceSetting());
+ setWebHooks(project.getWebHooks());
+ getContributedSettings().addAll(project.getContributedSettings().values());
+ }
+
public static ProjectSetting from(Project project) {
ProjectSetting setting = new ProjectSetting();
- setting.setBranchProtections(project.getBranchProtections());
- setting.setTagProtections(project.getTagProtections());
- setting.setBuildSetting(project.getBuildSetting());
- setting.setPackSetting(project.getPackSetting());
- setting.setIssueSetting(project.getIssueSetting());
- setting.setWikiSetting(project.getWikiSetting());
- setting.setNamedCodeCommentQueries(project.getNamedCodeCommentQueries());
- setting.setNamedCommitQueries(project.getNamedCommitQueries());
- setting.setPullRequestSetting(project.getPullRequestSetting());
- setting.setWorkspaceSetting(project.getWorkspaceSetting());
- setting.setWebHooks(project.getWebHooks());
- setting.getContributedSettings().addAll(project.getContributedSettings().values());
-
+ setting.populateFrom(project);
return setting;
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java
index e68d0522fd..ab3221c4a5 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java
@@ -54,6 +54,7 @@ import io.onedev.server.git.service.GitService;
import io.onedev.server.git.service.RefFacade;
import io.onedev.server.model.Project;
import io.onedev.server.model.User;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.FileCreateOrUpdateRequest;
import io.onedev.server.rest.resource.support.FileEditRequest;
@@ -83,7 +84,7 @@ public class RepositoryResource {
@Path("/{projectId}/branches")
@GET
public List<String> getBranches(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project))
throw new UnauthorizedException();
@@ -98,7 +99,7 @@ public class RepositoryResource {
@GET
@Nullable
public String getDefaultBranch(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project)) {
throw new UnauthorizedException();
}
@@ -110,7 +111,7 @@ public class RepositoryResource {
@Path("/{projectId}/default-branch")
@POST
public Response setDefaultBranch(@PathParam("projectId") Long projectId, @NotNull String defaultBranch) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canManageProject(project))
throw new UnauthorizedException();
@@ -129,7 +130,7 @@ public class RepositoryResource {
public RefResponse getBranch(
@PathParam("projectId") Long projectId,
@PathParam("branch") @Api(example="test-branch") String branchName) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project)) {
throw new UnauthorizedException();
}
@@ -150,7 +151,7 @@ public class RepositoryResource {
@Path("/{projectId}/branches")
@POST
public Response createBranch(@PathParam("projectId") Long projectId, @NotNull CreateBranchRequest request) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
User user = SecurityUtils.getUser();
if (!SecurityUtils.canWriteCode(project))
throw new UnauthorizedException();
@@ -176,7 +177,7 @@ public class RepositoryResource {
@DELETE
public Response deleteBranch(@PathParam("projectId") Long projectId,
@PathParam("branch") @Api(example="test-branch") String branchName) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canDeleteBranch(project, branchName))
throw new UnauthorizedException();
@@ -189,7 +190,7 @@ public class RepositoryResource {
@Path("/{projectId}/tags")
@GET
public List<String> getTags(@PathParam("projectId") Long projectId) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project)) {
throw new UnauthorizedException();
}
@@ -205,7 +206,7 @@ public class RepositoryResource {
public RefResponse getTag(
@PathParam("projectId") Long projectId,
@PathParam("tag") @Api(example="test-tag") String tagName) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project)) {
throw new UnauthorizedException();
@@ -227,7 +228,7 @@ public class RepositoryResource {
@Path("/{projectId}/tags")
@POST
public Response createTag(@PathParam("projectId") Long projectId, @NotNull CreateTagRequest request) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canCreateTag(project, request.getTagName())) {
throw new UnauthorizedException();
}
@@ -249,7 +250,7 @@ public class RepositoryResource {
public Response deleteTag(
@PathParam("projectId") Long projectId,
@PathParam("tag") @Api(example="test-tag") String tagName) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canDeleteTag(project, tagName)) {
throw new UnauthorizedException();
}
@@ -267,7 +268,7 @@ public class RepositoryResource {
@QueryParam("query") @Api(description="Syntax of this query is the same as in commits page", example="since tag(v4.0.0) until tag(v4.7.0)") String query,
@QueryParam("count") @Api(example="100", description="Number of commits to return") int count,
@QueryParam("field") @Api(exampleProvider = "getFieldsExample", description = "Fields to return. Unspecified fields will return as null in returned commit object") List<String> fields) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project)) {
throw new UnauthorizedException();
}
@@ -313,7 +314,7 @@ public class RepositoryResource {
public List<DirectoryChild> getDirectory(
@PathParam("projectId") Long projectId,
@PathParam("revisionAndDirectory") @NotEmpty @Api(example="some-branch-or-tag/path/to/directory") String revisionAndDirectory) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
if (!SecurityUtils.canReadCode(project)) {
throw new UnauthorizedException();
}
@@ -346,7 +347,7 @@ public class RepositoryResource {
@PathParam("projectId") Long projectId,
@QueryParam("revision") @NotEmpty @Api(example="some-branch-or-tag") String revision,
@QueryParam("file") @NotEmpty @Api(example="path/to/file") String file) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
file = GitUtils.normalizePath(file);
if (file == null)
throw new NotAcceptableException("File should be specified");
@@ -383,7 +384,7 @@ public class RepositoryResource {
@PathParam("projectId") Long projectId,
@PathParam("branchAndFile") @NotEmpty @Api(example="test-branch/path/to/file") String branchAndFile,
@NotNull FileEditRequest request) {
- Project project = projectService.load(projectId);
+ Project project = RestProjectUtils.loadProject(projectService, projectId);
List<String> revisionAndPathSegments = Splitter.on('/').splitToList(branchAndFile);
RevisionAndPath revisionAndPath;
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java
index 3fe95992a7..0950e9d752 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java
@@ -1,6 +1,7 @@
package io.onedev.server.rest.resource;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -25,8 +26,10 @@ import org.apache.shiro.authz.UnauthorizedException;
import io.onedev.commons.utils.ExplicitException;
import io.onedev.server.OneDev;
import io.onedev.server.data.migration.VersionedXmlDoc;
-import io.onedev.server.service.AuditService;
-import io.onedev.server.service.SettingService;
+import io.onedev.server.model.BaseAuthorization;
+import io.onedev.server.model.GroupAuthorization;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.UserAuthorization;
import io.onedev.server.model.support.administration.BackupSetting;
import io.onedev.server.model.support.administration.GlobalBuildSetting;
import io.onedev.server.model.support.administration.GlobalWorkspaceSetting;
@@ -42,8 +45,14 @@ import io.onedev.server.model.support.administration.authenticator.Authenticator
import io.onedev.server.model.support.administration.emailtemplates.EmailTemplates;
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.model.support.administration.mailservice.MailConnector;
+import io.onedev.server.persistence.TransactionService;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.rest.resource.support.ProjectDefaults;
import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.AuditService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.service.SettingService;
import io.onedev.server.web.page.layout.ContributedAdministrationSetting;
@Path("/settings")
@@ -57,6 +66,12 @@ public class SettingResource {
private final AuditService auditService;
private final Validator validator;
+
+ @Inject
+ private ProjectService projectService;
+
+ @Inject
+ private TransactionService transactionService;
@Inject
public SettingResource(SettingService settingService, AuditService auditService, Validator validator) {
@@ -444,4 +459,57 @@ public class SettingResource {
return Response.ok().build();
}
+ private Project getDefaultsProject() {
+ RestProjectUtils.checkProjectDefaultsPermission();
+ return projectService.load(Project.DEFAULT_ID);
+ }
+
+ @Api(order=2900, description="Get shared project defaults. Requires an active subscription")
+ @Path("/project-defaults")
+ @GET
+ public ProjectDefaults getProjectDefaults() {
+ return ProjectDefaults.from(getDefaultsProject());
+ }
+
+ @Api(order=3000, description="Replace shared project defaults. Requires an active subscription")
+ @Path("/project-defaults")
+ @POST
+ public Response setProjectDefaults(@NotNull ProjectDefaults defaults) {
+ var project = getDefaultsProject();
+ var violations = validator.validate(defaults);
+ if (!violations.isEmpty()) {
+ var violation = violations.iterator().next();
+ throw new ExplicitException(violation.getPropertyPath() + ": " + violation.getMessage());
+ }
+ transactionService.run(() -> {
+ var oldAuditContent = VersionedXmlDoc.fromBean(ProjectDefaults.from(project)).toXML();
+ defaults.populate(project);
+ projectService.update(project);
+ auditService.audit(project, "changed project defaults via RESTful API",
+ oldAuditContent, VersionedXmlDoc.fromBean(ProjectDefaults.from(project)).toXML());
+ });
+ return Response.ok().build();
+ }
+
+ @Api(order=3300, description="Get project default user authorizations. Use user-authorizations resource to add or remove entries")
+ @Path("/project-defaults/user-authorizations")
+ @GET
+ public Collection<UserAuthorization> getProjectDefaultUserAuthorizations() {
+ return getDefaultsProject().getUserAuthorizations();
+ }
+
+ @Api(order=3400, description="Get project default group authorizations. Use group-authorizations resource to add or remove entries")
+ @Path("/project-defaults/group-authorizations")
+ @GET
+ public Collection<GroupAuthorization> getProjectDefaultGroupAuthorizations() {
+ return getDefaultsProject().getGroupAuthorizations();
+ }
+
+ @Api(order=3500, description="Get project default base authorizations. Use base-authorizations resource to add or remove entries")
+ @Path("/project-defaults/base-authorizations")
+ @GET
+ public Collection<BaseAuthorization> getProjectDefaultBaseAuthorizations() {
+ return getDefaultsProject().getBaseAuthorizations();
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/UserAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/UserAuthorizationResource.java
index 0bbbf7396d..6905f10996 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/UserAuthorizationResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/UserAuthorizationResource.java
@@ -13,14 +13,12 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
-import org.apache.shiro.authz.UnauthorizedException;
-
import io.onedev.server.data.migration.VersionedXmlDoc;
import io.onedev.server.service.AuditService;
import io.onedev.server.service.UserAuthorizationService;
import io.onedev.server.model.UserAuthorization;
import io.onedev.server.rest.annotation.Api;
-import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.rest.RestProjectUtils;
@Path("/user-authorizations")
@Consumes(MediaType.APPLICATION_JSON)
@@ -43,16 +41,14 @@ public class UserAuthorizationResource {
@GET
public UserAuthorization getAuthorization(@PathParam("authorizationId") Long authorizationId) {
UserAuthorization authorization = authorizationService.load(authorizationId);
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
return authorization;
}
@Api(order=200, description="Create user authorization")
@POST
public Long createAuthorization(@NotNull UserAuthorization authorization) {
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
authorizationService.createOrUpdate(authorization);
var newAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(null, "created user authorization via RESTful API", null, newAuditContent);
@@ -64,8 +60,7 @@ public class UserAuthorizationResource {
@DELETE
public Response deleteAuthorization(@PathParam("authorizationId") Long authorizationId) {
UserAuthorization authorization = authorizationService.load(authorizationId);
- if (!SecurityUtils.canManageProject(authorization.getProject()))
- throw new UnauthorizedException();
+ RestProjectUtils.checkAuthorizationPermission(authorization.getProject());
authorizationService.delete(authorization);
var oldAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(null, "deleted user authorization via RESTful API", oldAuditContent, null);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/WorkspaceResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/WorkspaceResource.java
index 091b5aa6fa..7939f4c234 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/WorkspaceResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/WorkspaceResource.java
@@ -30,6 +30,7 @@ import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.Workspace;
import io.onedev.server.model.Workspace.Status;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -103,7 +104,7 @@ public class WorkspaceResource {
if (user == null)
throw new UnauthorizedException();
- Project project = projectService.load(data.getProjectId());
+ Project project = RestProjectUtils.loadProject(projectService, data.getProjectId());
if (!SecurityUtils.canCreateWorkspaces(subject, project))
throw new UnauthorizedException();
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/support/ProjectDefaults.java b/server-core/src/main/java/io/onedev/server/rest/resource/support/ProjectDefaults.java
new file mode 100644
index 0000000000..eb4279e30b
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/support/ProjectDefaults.java
@@ -0,0 +1,368 @@
+package io.onedev.server.rest.resource.support;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
+
+import io.onedev.server.annotation.BranchName;
+import io.onedev.server.annotation.ClassValidating;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.support.CodeIndexingSetting;
+import io.onedev.server.model.support.ProjectAiSetting;
+import io.onedev.server.model.support.WebHook;
+import io.onedev.server.model.support.build.BuildPreservation;
+import io.onedev.server.model.support.build.DefaultFixedIssueFilter;
+import io.onedev.server.model.support.build.JobProperty;
+import io.onedev.server.model.support.build.JobSecret;
+import io.onedev.server.model.support.build.ProjectBuildSetting;
+import io.onedev.server.model.support.code.BranchProtection;
+import io.onedev.server.model.support.code.TagProtection;
+import io.onedev.server.model.support.issue.ProjectIssueSetting;
+import io.onedev.server.model.support.pullrequest.MergeStrategy;
+import io.onedev.server.model.support.pullrequest.ProjectPullRequestSetting;
+import io.onedev.server.model.support.wiki.WikiSetting;
+import io.onedev.server.model.support.workspace.spec.WorkspaceSpec;
+import io.onedev.server.validation.Validatable;
+import io.onedev.server.web.page.project.setting.ContributedProjectSetting;
+
+/** Only settings inherited from the defaults project belong in this API. */
+@ClassValidating
+public class ProjectDefaults implements Serializable, Validatable {
+
+ private static final long serialVersionUID = 1L;
+
+ private ArrayList<BranchProtection> branchProtections = new ArrayList<>();
+
+ private ArrayList<TagProtection> tagProtections = new ArrayList<>();
+
+ private CodeIndexingSetting codeIndexingSetting = new CodeIndexingSetting();
+
+ private ProjectAiSetting aiSetting = new ProjectAiSetting();
+
+ private ArrayList<WorkspaceSpec> workspaceSpecs = new ArrayList<>();
+
+ private WikiSetting wikiSetting = new WikiSetting();
+
+ private ArrayList<WebHook> webHooks = new ArrayList<>();
+
+ private ArrayList<ContributedProjectSetting> contributedSettings = new ArrayList<>();
+
+ private BuildDefaults buildSetting = new BuildDefaults();
+
+ private IssueDefaults issueSetting = new IssueDefaults();
+
+ private PullRequestDefaults pullRequestSetting = new PullRequestDefaults();
+
+ @NotNull
+ public ArrayList<@NotNull @Valid BranchProtection> getBranchProtections() {
+ return branchProtections;
+ }
+
+ public void setBranchProtections(ArrayList<BranchProtection> branchProtections) {
+ this.branchProtections = branchProtections;
+ }
+
+ @NotNull
+ public ArrayList<@NotNull @Valid TagProtection> getTagProtections() {
+ return tagProtections;
+ }
+
+ public void setTagProtections(ArrayList<TagProtection> tagProtections) {
+ this.tagProtections = tagProtections;
+ }
+
+ @Valid
+ @NotNull
+ public CodeIndexingSetting getCodeIndexingSetting() {
+ return codeIndexingSetting;
+ }
+
+ public void setCodeIndexingSetting(CodeIndexingSetting codeIndexingSetting) {
+ this.codeIndexingSetting = codeIndexingSetting;
+ }
+
+ @Valid
+ @NotNull
+ public ProjectAiSetting getAiSetting() {
+ return aiSetting;
+ }
+
+ public void setAiSetting(ProjectAiSetting aiSetting) {
+ this.aiSetting = aiSetting;
+ }
+
+ @NotNull
+ public ArrayList<@NotNull @Valid WorkspaceSpec> getWorkspaceSpecs() {
+ return workspaceSpecs;
+ }
+
+ public void setWorkspaceSpecs(ArrayList<WorkspaceSpec> workspaceSpecs) {
+ this.workspaceSpecs = workspaceSpecs;
+ }
+
+ @Valid
+ @NotNull
+ public WikiSetting getWikiSetting() {
+ return wikiSetting;
+ }
+
+ public void setWikiSetting(WikiSetting wikiSetting) {
+ this.wikiSetting = wikiSetting;
+ }
+
+ @NotNull
+ public ArrayList<@NotNull @Valid WebHook> getWebHooks() {
+ return webHooks;
+ }
+
+ public void setWebHooks(ArrayList<WebHook> webHooks) {
+ this.webHooks = webHooks;
+ }
+
+ @NotNull
+ public ArrayList<@NotNull @Valid ContributedProjectSetting> getContributedSettings() {
+ return contributedSettings;
+ }
+
+ public void setContributedSettings(ArrayList<ContributedProjectSetting> contributedSettings) {
+ this.contributedSettings = contributedSettings;
+ }
+
+ @Valid
+ @NotNull
+ public BuildDefaults getBuildSetting() {
+ return buildSetting;
+ }
+
+ public void setBuildSetting(BuildDefaults buildSetting) {
+ this.buildSetting = buildSetting;
+ }
+
+ @Valid
+ @NotNull
+ public IssueDefaults getIssueSetting() {
+ return issueSetting;
+ }
+
+ public void setIssueSetting(IssueDefaults issueSetting) {
+ this.issueSetting = issueSetting;
+ }
+
+ @Valid
+ @NotNull
+ public PullRequestDefaults getPullRequestSetting() {
+ return pullRequestSetting;
+ }
+
+ public void setPullRequestSetting(PullRequestDefaults pullRequestSetting) {
+ this.pullRequestSetting = pullRequestSetting;
+ }
+
+ @Override
+ public boolean isValid(ConstraintValidatorContext context) {
+ var names = new HashSet<String>();
+ if (workspaceSpecs != null) {
+ for (var spec: workspaceSpecs) {
+ if (spec != null && spec.getName() != null && !names.add(spec.getName())) {
+ context.disableDefaultConstraintViolation();
+ context.buildConstraintViolationWithTemplate("Workspace spec names must be unique")
+ .addPropertyNode("workspaceSpecs").addConstraintViolation();
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ public void populate(Project project) {
+ project.setBranchProtections(getBranchProtections());
+ project.setTagProtections(getTagProtections());
+ project.setCodeIndexingSetting(getCodeIndexingSetting());
+ project.setAiSetting(getAiSetting());
+ project.setWorkspaceSpecs(getWorkspaceSpecs());
+ project.setWikiSetting(getWikiSetting());
+ project.setWebHooks(getWebHooks());
+ var settings = new LinkedHashMap<String, ContributedProjectSetting>();
+ for (var setting: getContributedSettings())
+ settings.put(setting.getClass().getName(), setting);
+ project.setContributedSettings(settings);
+ getBuildSetting().populate(project.getBuildSetting());
+ getIssueSetting().populate(project.getIssueSetting());
+ getPullRequestSetting().populate(project.getPullRequestSetting());
+ }
+
+ public static ProjectDefaults from(Project project) {
+ var defaults = new ProjectDefaults();
+ defaults.setBranchProtections(project.getBranchProtections());
+ defaults.setTagProtections(project.getTagProtections());
+ defaults.setCodeIndexingSetting(project.getCodeIndexingSetting());
+ defaults.setAiSetting(project.getAiSetting());
+ defaults.setWorkspaceSpecs(project.getWorkspaceSpecs());
+ defaults.setWikiSetting(project.getWikiSetting());
+ defaults.setWebHooks(project.getWebHooks());
+ defaults.getContributedSettings().addAll(project.getContributedSettings().values());
+ defaults.setBuildSetting(BuildDefaults.from(project.getBuildSetting()));
+ defaults.setIssueSetting(IssueDefaults.from(project.getIssueSetting()));
+ defaults.setPullRequestSetting(PullRequestDefaults.from(project.getPullRequestSetting()));
+ return defaults;
+ }
+
+ public static class BuildDefaults implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private List<JobProperty> jobProperties = new ArrayList<>();
+
+ private List<JobSecret> jobSecrets = new ArrayList<>();
+
+ private List<BuildPreservation> buildPreservations = new ArrayList<>();
+
+ private List<DefaultFixedIssueFilter> defaultFixedIssueFilters = new ArrayList<>();
+
+ private Integer cachePreserveDays;
+
+ @NotNull
+ public List<@NotNull @Valid JobProperty> getJobProperties() {
+ return jobProperties;
+ }
+
+ public void setJobProperties(List<JobProperty> jobProperties) {
+ this.jobProperties = jobProperties;
+ }
+
+ @NotNull
+ public List<@NotNull @Valid JobSecret> getJobSecrets() {
+ return jobSecrets;
+ }
+
+ public void setJobSecrets(List<JobSecret> jobSecrets) {
+ this.jobSecrets = jobSecrets;
+ }
+
+ @NotNull
+ public List<@NotNull @Valid BuildPreservation> getBuildPreservations() {
+ return buildPreservations;
+ }
+
+ public void setBuildPreservations(List<BuildPreservation> buildPreservations) {
+ this.buildPreservations = buildPreservations;
+ }
+
+ @NotNull
+ public List<@NotNull @Valid DefaultFixedIssueFilter> getDefaultFixedIssueFilters() {
+ return defaultFixedIssueFilters;
+ }
+
+ public void setDefaultFixedIssueFilters(List<DefaultFixedIssueFilter> defaultFixedIssueFilters) {
+ this.defaultFixedIssueFilters = defaultFixedIssueFilters;
+ }
+
+ public Integer getCachePreserveDays() {
+ return cachePreserveDays;
+ }
+
+ public void setCachePreserveDays(Integer cachePreserveDays) {
+ this.cachePreserveDays = cachePreserveDays;
+ }
+
+ private void populate(ProjectBuildSetting setting) {
+ setting.setJobProperties(getJobProperties());
+ setting.setJobSecrets(getJobSecrets());
+ setting.setBuildPreservations(getBuildPreservations());
+ setting.setDefaultFixedIssueFilters(getDefaultFixedIssueFilters());
+ setting.setCachePreserveDays(getCachePreserveDays());
+ }
+
+ private static BuildDefaults from(ProjectBuildSetting setting) {
+ var defaults = new BuildDefaults();
+ defaults.setJobProperties(setting.getJobProperties());
+ defaults.setJobSecrets(setting.getJobSecrets());
+ defaults.setBuildPreservations(setting.getBuildPreservations());
+ defaults.setDefaultFixedIssueFilters(setting.getDefaultFixedIssueFilters());
+ defaults.setCachePreserveDays(setting.getCachePreserveDays());
+ return defaults;
+ }
+ }
+
+ public static class IssueDefaults implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String branchPrefix;
+
+ @BranchName
+ public String getBranchPrefix() {
+ return branchPrefix;
+ }
+
+ public void setBranchPrefix(String branchPrefix) {
+ this.branchPrefix = branchPrefix;
+ }
+
+ private void populate(ProjectIssueSetting setting) {
+ setting.setBranchPrefix(getBranchPrefix());
+ }
+
+ private static IssueDefaults from(ProjectIssueSetting setting) {
+ var defaults = new IssueDefaults();
+ defaults.setBranchPrefix(setting.getBranchPrefix());
+ return defaults;
+ }
+ }
+
+ public static class PullRequestDefaults implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private MergeStrategy defaultMergeStrategy;
+
+ private List<String> defaultAssignees = new ArrayList<>();
+
+ private Boolean deleteSourceBranchAfterMerge;
+
+ public MergeStrategy getDefaultMergeStrategy() {
+ return defaultMergeStrategy;
+ }
+
+ public void setDefaultMergeStrategy(MergeStrategy defaultMergeStrategy) {
+ this.defaultMergeStrategy = defaultMergeStrategy;
+ }
+
+ @NotNull
+ public List<@NotNull String> getDefaultAssignees() {
+ return defaultAssignees;
+ }
+
+ public void setDefaultAssignees(List<String> defaultAssignees) {
+ this.defaultAssignees = defaultAssignees;
+ }
+
+ public Boolean getDeleteSourceBranchAfterMerge() {
+ return deleteSourceBranchAfterMerge;
+ }
+
+ public void setDeleteSourceBranchAfterMerge(Boolean deleteSourceBranchAfterMerge) {
+ this.deleteSourceBranchAfterMerge = deleteSourceBranchAfterMerge;
+ }
+
+ private void populate(ProjectPullRequestSetting setting) {
+ setting.setDefaultMergeStrategy(getDefaultMergeStrategy());
+ setting.setDefaultAssignees(getDefaultAssignees());
+ setting.setDeleteSourceBranchAfterMerge(getDeleteSourceBranchAfterMerge());
+ }
+
+ private static PullRequestDefaults from(ProjectPullRequestSetting setting) {
+ var defaults = new PullRequestDefaults();
+ defaults.setDefaultMergeStrategy(setting.getDefaultMergeStrategy());
+ defaults.setDefaultAssignees(setting.getDefaultAssignees());
+ defaults.setDeleteSourceBranchAfterMerge(setting.getDeleteSourceBranchAfterMerge());
+ return defaults;
+ }
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/security/AuthorizationInfoCache.java b/server-core/src/main/java/io/onedev/server/security/AuthorizationInfoCache.java
new file mode 100644
index 0000000000..beb49ffdc4
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/security/AuthorizationInfoCache.java
@@ -0,0 +1,37 @@
+package io.onedev.server.security;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.jspecify.annotations.Nullable;
+
+/** Shares authorization information within a synchronous operation and its nested calls. */
+final class AuthorizationInfoCache implements AutoCloseable {
+
+ private static final ThreadLocal<Map<String, AuthorizationInfo>> cache = new ThreadLocal<>();
+
+ private final boolean owner;
+
+ private AuthorizationInfoCache() {
+ owner = cache.get() == null;
+ if (owner)
+ cache.set(new HashMap<>());
+ }
+
+ static AuthorizationInfoCache open() {
+ return new AuthorizationInfoCache();
+ }
+
+ @Nullable
+ static Map<String, AuthorizationInfo> get() {
+ return cache.get();
+ }
+
+ @Override
+ public void close() {
+ if (owner)
+ cache.remove();
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java b/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java
index f2e434b959..b9d967e4d7 100644
--- a/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java
+++ b/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java
@@ -89,11 +89,13 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
var accessToken = SecurityUtils.getAccessToken(principal);
if (accessToken != null) {
- var owner = accessToken.getOwner();
- for (var authorization: accessToken.getAuthorizations()) {
- var project = authorization.getProject();
- if (SecurityUtils.canManageProject(owner.asSubject(), project))
- permissions.add(new ProjectPermission(project, authorization.getRole()));
+ try (var ignored = AuthorizationInfoCache.open()) {
+ var ownerSubject = accessToken.getOwner().asSubject();
+ for (var authorization: accessToken.getAuthorizations()) {
+ var project = authorization.getProject();
+ if (SecurityUtils.canManageProject(ownerSubject, project))
+ permissions.add(new ProjectPermission(project, authorization.getRole()));
+ }
}
}
@@ -106,7 +108,7 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
do {
if (project.isPermittedByLoginUser(privilege))
return true;
- project = project.getParent();
+ project = project.getSettingsParent();
} while (project != null);
}
return false;
@@ -148,14 +150,20 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String principal = (String) principals.getPrimaryPrincipal();
RequestCycle requestCycle = RequestCycle.get();
+ Map<String, AuthorizationInfo> authorizationInfos;
if (requestCycle != null) {
- Map<String, AuthorizationInfo> authorizationInfos = requestCycle.getMetaData(AUTHORIZATION_INFOS);
+ authorizationInfos = requestCycle.getMetaData(AUTHORIZATION_INFOS);
if (authorizationInfos == null) {
authorizationInfos = new HashMap<>();
requestCycle.setMetaData(AUTHORIZATION_INFOS, authorizationInfos);
}
+ } else {
+ authorizationInfos = AuthorizationInfoCache.get();
+ }
+ if (authorizationInfos != null) {
AuthorizationInfo authorizationInfo = authorizationInfos.get(principal);
if (authorizationInfo == null) {
+ // Token authorization may populate its owner's entry while this entry is built.
authorizationInfo = newAuthorizationInfo(principal);
authorizationInfos.put(principal, authorizationInfo);
}
@@ -179,4 +187,4 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
return new ManagedSerializedForm(AuthorizingService.class);
}
-}
\ No newline at end of file
+}
diff --git a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
index 43318aea1f..ab465bd5f0 100644
--- a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
+++ b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
@@ -3,9 +3,11 @@ package io.onedev.server.security;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
+import io.onedev.server.web.util.WicketUtils;
import io.onedev.server.web.util.WikiUtils;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -419,41 +421,45 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
}
public static boolean isAssignedRole(Subject subject, Project project, Role role) {
- String principal = (String) subject.getPrincipal();
- var user = getAuthUser(principal);
- if (user != null) {
- for (UserAuthorization authorization: user.getProjectAuthorizations()) {
- Project authorizedProject = authorization.getProject();
- if (authorization.getRole().equals(role) && authorizedProject.isSelfOrAncestorOf(project))
- return true;
- }
-
- for (Group group: user.getGroups()) {
- for (GroupAuthorization authorization: group.getAuthorizations()) {
+ try (var ignored = AuthorizationInfoCache.open()) {
+ String principal = (String) subject.getPrincipal();
+ var user = getAuthUser(principal);
+ if (user != null) {
+ for (UserAuthorization authorization: user.getProjectAuthorizations()) {
Project authorizedProject = authorization.getProject();
- if (authorization.getRole().equals(role) && authorizedProject.isSelfOrAncestorOf(project))
+ if (authorization.getRole().equals(role) && authorizedProject.isSelfOrSettingsAncestorOf(project))
return true;
}
- }
- return isAssignedDefaultRole(project, role);
- }
+ for (Group group: user.getGroups()) {
+ for (GroupAuthorization authorization: group.getAuthorizations()) {
+ Project authorizedProject = authorization.getProject();
+ if (authorization.getRole().equals(role) && authorizedProject.isSelfOrSettingsAncestorOf(project))
+ return true;
+ }
+ }
+
+ return isAssignedDefaultRole(project, role);
+ }
- var accessToken = getAccessToken(principal);
- if (accessToken != null) {
- for (var authorization: accessToken.getAuthorizations()) {
- Project authorizedProject = authorization.getProject();
- if (authorization.getRole().equals(role) && authorizedProject.isSelfOrAncestorOf(project))
- return true;
- }
- return isAssignedDefaultRole(project, role);
+ var accessToken = getAccessToken(principal);
+ if (accessToken != null) {
+ var ownerSubject = accessToken.getOwner().asSubject();
+ for (var authorization: accessToken.getAuthorizations()) {
+ Project authorizedProject = authorization.getProject();
+ if (authorization.getRole().equals(role) && authorizedProject.isSelfOrSettingsAncestorOf(project)
+ && canManageProject(ownerSubject, authorizedProject))
+ return true;
+ }
+ return isAssignedDefaultRole(project, role);
+ }
+ return OneDev.getInstance(SettingService.class).getSecuritySetting().isEnableAnonymousAccess()
+ && isAssignedDefaultRole(project, role);
}
- return OneDev.getInstance(SettingService.class).getSecuritySetting().isEnableAnonymousAccess()
- && isAssignedDefaultRole(project, role);
}
private static boolean isAssignedDefaultRole(Project project, Role role) {
- return role.getBaseAuthorizations().stream().anyMatch(it->it.getProject().isSelfOrAncestorOf(project));
+ return role.getBaseAuthorizations().stream().anyMatch(it->it.getProject().isSelfOrSettingsAncestorOf(project));
}
public static boolean canAccessProject(Project project) {
@@ -780,12 +786,23 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
return null;
}
+ private static Collection<Long> getAuthorizedProjectIds(ProjectCache cache, Project project) {
+ if (Project.DEFAULT_ID.equals(project.getId())) {
+ if (WicketUtils.isSubscriptionActive())
+ return cache.keySet();
+ else
+ return Collections.emptySet();
+ } else {
+ return cache.getSubtreeIds(project.getId());
+ }
+ }
+
private static void addIdsPermittedByDefaultRole(ProjectCache cache, Collection<Long> projectIds,
Permission permission) {
var baseAuthorizationService = OneDev.getInstance(BaseAuthorizationService.class);
for (var authorization: baseAuthorizationService.query()) {
if (authorization.getRole().implies(permission))
- projectIds.addAll(cache.getSubtreeIds(authorization.getProject().getId()));
+ projectIds.addAll(getAuthorizedProjectIds(cache, authorization.getProject()));
}
}
@@ -806,45 +823,49 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
}
public static Collection<Project> getAuthorizedProjects(Subject subject, @Nullable ProjectCache cache, BasePermission permission) {
- var projectService = OneDev.getInstance(ProjectService.class);
- String principal = (String) subject.getPrincipal();
- var user = getAuthUser(principal);
- var accessToken = getAccessToken(principal);
- if (permission.isApplicable(UserFacade.of(getUser(user, accessToken)))) {
- if (cache == null)
- cache = projectService.cloneCache();
- Collection<Long> authorizedProjectIds = new HashSet<>();
- if (user != null) {
- if (user.isRoot() || user.isSystem()) {
- return cache.getProjects();
- } else {
- for (Group group : user.getGroups()) {
- if (group.isAdministrator())
- return cache.getProjects();
- for (GroupAuthorization authorization : group.getAuthorizations()) {
- if (authorization.getRole().implies(permission))
- authorizedProjectIds.addAll(cache.getSubtreeIds(authorization.getProject().getId()));
+ try (var ignored = AuthorizationInfoCache.open()) {
+ var projectService = OneDev.getInstance(ProjectService.class);
+ String principal = (String) subject.getPrincipal();
+ var user = getAuthUser(principal);
+ var accessToken = getAccessToken(principal);
+ if (permission.isApplicable(UserFacade.of(getUser(user, accessToken)))) {
+ if (cache == null)
+ cache = projectService.cloneCache();
+ Collection<Long> authorizedProjectIds = new HashSet<>();
+ if (user != null) {
+ if (user.isRoot() || user.isSystem()) {
+ return cache.getProjects();
+ } else {
+ for (Group group : user.getGroups()) {
+ if (group.isAdministrator())
+ return cache.getProjects();
+ for (GroupAuthorization authorization : group.getAuthorizations()) {
+ if (authorization.getRole().implies(permission))
+ authorizedProjectIds.addAll(getAuthorizedProjectIds(cache, authorization.getProject()));
+ }
}
- }
- for (UserAuthorization authorization : user.getProjectAuthorizations()) {
- if (authorization.getRole().implies(permission))
- authorizedProjectIds.addAll(cache.getSubtreeIds(authorization.getProject().getId()));
+ for (UserAuthorization authorization : user.getProjectAuthorizations()) {
+ if (authorization.getRole().implies(permission))
+ authorizedProjectIds.addAll(getAuthorizedProjectIds(cache, authorization.getProject()));
+ }
}
}
- }
- if (accessToken != null) {
- for (var authorization : accessToken.getAuthorizations()) {
- if (authorization.getRole().implies(permission))
- authorizedProjectIds.addAll(cache.getSubtreeIds(authorization.getProject().getId()));
+ if (accessToken != null) {
+ var ownerSubject = accessToken.getOwner().asSubject();
+ for (var authorization : accessToken.getAuthorizations()) {
+ if (authorization.getRole().implies(permission)
+ && canManageProject(ownerSubject, authorization.getProject()))
+ authorizedProjectIds.addAll(getAuthorizedProjectIds(cache, authorization.getProject()));
+ }
}
- }
- if (!isAnonymous(principal) || getSettingService().getSecuritySetting().isEnableAnonymousAccess())
- addIdsPermittedByDefaultRole(cache, authorizedProjectIds, permission);
+ if (!isAnonymous(principal) || getSettingService().getSecuritySetting().isEnableAnonymousAccess())
+ addIdsPermittedByDefaultRole(cache, authorizedProjectIds, permission);
- return authorizedProjectIds.stream().map(projectService::load).collect(toSet());
- } else {
- return new HashSet<>();
+ return authorizedProjectIds.stream().map(projectService::load).collect(toSet());
+ } else {
+ return new HashSet<>();
+ }
}
}
@@ -876,7 +897,7 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
authorizedUsers.addAll(authorization.getGroup().getMembers());
}
}
- current = current.getParent();
+ current = current.getSettingsParent();
} while (current != null);
if (permission instanceof ConfidentialIssuePermission) {
@@ -901,47 +922,53 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
public static Map<String, Collection<String>> getAccessibleReportNames(Project project, Class<?> metricClass,
Map<String, Collection<String>> availableReportNames) {
- Map<String, Collection<String>> accessibleReportNames = new HashMap<>();
- var subject = getSubject();
- if (subject.isPermitted(new SystemAdministration())) {
- for (Map.Entry<String, Collection<String>> entry: availableReportNames.entrySet())
- accessibleReportNames.put(entry.getKey(), new HashSet<>(entry.getValue()));
- } else {
- String principal = (String) subject.getPrincipal();
- var user = getAuthUser(principal);
- if (user != null) {
- for (UserAuthorization authorization: user.getProjectAuthorizations()) {
- if (project.equals(authorization.getProject())) {
- populateAccessibleReportNames(accessibleReportNames, availableReportNames,
- project, authorization.getRole());
+ try (var ignored = AuthorizationInfoCache.open()) {
+ Map<String, Collection<String>> accessibleReportNames = new HashMap<>();
+ var subject = getSubject();
+ if (subject.isPermitted(new SystemAdministration())) {
+ for (Map.Entry<String, Collection<String>> entry: availableReportNames.entrySet())
+ accessibleReportNames.put(entry.getKey(), new HashSet<>(entry.getValue()));
+ } else {
+ String principal = (String) subject.getPrincipal();
+ var user = getAuthUser(principal);
+ if (user != null) {
+ for (UserAuthorization authorization: user.getProjectAuthorizations()) {
+ if (authorization.getProject().isSelfOrSettingsAncestorOf(project)) {
+ populateAccessibleReportNames(accessibleReportNames, availableReportNames,
+ project, authorization.getRole());
+ }
+ }
+ for (Group group: user.getGroups()) {
+ for (GroupAuthorization authorization: group.getAuthorizations()) {
+ if (authorization.getProject().isSelfOrSettingsAncestorOf(project)) {
+ populateAccessibleReportNames(accessibleReportNames, availableReportNames,
+ project, authorization.getRole());
+ }
+ }
}
}
- for (Group group: user.getGroups()) {
- for (GroupAuthorization authorization: group.getAuthorizations()) {
- if (project.equals(authorization.getProject())) {
+ var accessToken = getAccessToken(principal);
+ if (accessToken != null) {
+ var ownerSubject = accessToken.getOwner().asSubject();
+ for (var authorization: accessToken.getAuthorizations()) {
+ if (authorization.getProject().isSelfOrSettingsAncestorOf(project)
+ && canManageProject(ownerSubject, authorization.getProject())) {
populateAccessibleReportNames(accessibleReportNames, availableReportNames,
project, authorization.getRole());
}
}
}
- }
- var accessToken = getAccessToken(principal);
- if (accessToken != null) {
- for (var authorization: accessToken.getAuthorizations()) {
- if (project.equals(authorization.getProject())) {
- populateAccessibleReportNames(accessibleReportNames, availableReportNames,
- project, authorization.getRole());
+ if (!isAnonymous(principal) || getSettingService().getSecuritySetting().isEnableAnonymousAccess()) {
+ for (var current = project; current != null; current = current.getSettingsParent()) {
+ for (var authorization: current.getBaseAuthorizations()) {
+ populateAccessibleReportNames(accessibleReportNames, availableReportNames,
+ project, authorization.getRole());
+ }
}
}
}
- if (!isAnonymous(principal) || getSettingService().getSecuritySetting().isEnableAnonymousAccess()) {
- for (var authorization: project.getBaseAuthorizations()) {
- populateAccessibleReportNames(accessibleReportNames, availableReportNames,
- project, authorization.getRole());
- }
- }
+ return accessibleReportNames;
}
- return accessibleReportNames;
}
}
diff --git a/server-core/src/main/java/io/onedev/server/security/permission/ProjectPermission.java b/server-core/src/main/java/io/onedev/server/security/permission/ProjectPermission.java
index a90617246d..f864947615 100644
--- a/server-core/src/main/java/io/onedev/server/security/permission/ProjectPermission.java
+++ b/server-core/src/main/java/io/onedev/server/security/permission/ProjectPermission.java
@@ -28,7 +28,7 @@ public class ProjectPermission implements BasePermission {
public boolean implies(Permission p) {
if (p instanceof ProjectPermission) {
ProjectPermission projectPermission = (ProjectPermission) p;
- return project.isSelfOrAncestorOf(projectPermission.project)
+ return project.isSelfOrSettingsAncestorOf(projectPermission.project)
&& privilege.implies(projectPermission.privilege);
} else {
return false;
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultGroupService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultGroupService.java
index 73e511eaa4..28dc034264 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultGroupService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultGroupService.java
@@ -2,6 +2,7 @@ package io.onedev.server.service.impl;
import static io.onedev.server.persistence.dao.Restrictions.eq;
+import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
@@ -35,6 +36,7 @@ import io.onedev.server.service.SettingService;
import io.onedev.server.util.facade.GroupCache;
import io.onedev.server.util.facade.GroupFacade;
import io.onedev.server.util.usage.Usage;
+import io.onedev.server.web.util.WicketUtils;
@Singleton
public class DefaultGroupService extends BaseEntityService<Group> implements GroupService {
@@ -77,7 +79,10 @@ public class DefaultGroupService extends BaseEntityService<Group> implements Gro
public void update(Group group, String oldName) {
Preconditions.checkState(!group.isNew());
if (oldName != null && !oldName.equals(group.getName())) {
- for (Project project: projectService.query()) {
+ var projects = new ArrayList<>(projectService.query());
+ if (WicketUtils.isSubscriptionActive())
+ projects.add(projectService.load(Project.DEFAULT_ID));
+ for (Project project: projects) {
try {
for (BranchProtection protection : project.getBranchProtections())
protection.onRenameGroup(oldName, group.getName());
@@ -98,7 +103,10 @@ public class DefaultGroupService extends BaseEntityService<Group> implements Gro
@Override
public void delete(Group group) {
Usage usage = new Usage();
- for (Project project: projectService.query()) {
+ var projects = new ArrayList<>(projectService.query());
+ if (WicketUtils.isSubscriptionActive())
+ projects.add(projectService.load(Project.DEFAULT_ID));
+ for (Project project: projects) {
try {
Usage usageInProject = new Usage();
for (BranchProtection protection : project.getBranchProtections())
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueService.java
index e0013c0785..b8b9e18a63 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueService.java
@@ -131,6 +131,7 @@ import io.onedev.server.web.component.issue.workflowreconcile.UndefinedFieldReso
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedFieldValue;
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedFieldValuesResolution;
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedStateResolution;
+import io.onedev.server.web.util.WicketUtils;
@Singleton
public class DefaultIssueService extends BaseEntityService<Issue> implements IssueService, Serializable {
@@ -563,6 +564,13 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
}
+ private List<Project> getProjectsForWorkflowReconciliation() {
+ var projects = new ArrayList<>(projectService.query());
+ if (WicketUtils.isSubscriptionActive())
+ projects.add(projectService.load(Project.DEFAULT_ID));
+ return projects;
+ }
+
@Sessional
@Override
public Collection<String> getUndefinedStates() {
@@ -580,7 +588,7 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
undefinedStates.add(state);
}
- for (Project project: projectService.query()) {
+ for (Project project: getProjectsForWorkflowReconciliation()) {
undefinedStates.addAll(project.getIssueSetting().getUndefinedStates());
undefinedStates.addAll(project.getBuildSetting().getUndefinedStates());
}
@@ -623,7 +631,7 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
undefinedFields.add(fieldName);
}
- for (Project project: projectService.query()) {
+ for (Project project: getProjectsForWorkflowReconciliation()) {
undefinedFields.addAll(project.getIssueSetting().getUndefinedFields());
undefinedFields.addAll(project.getBuildSetting().getUndefinedFields());
}
@@ -672,7 +680,7 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
}
}
- for (Project project: projectService.query()) {
+ for (Project project: getProjectsForWorkflowReconciliation()) {
undefinedFieldValues.addAll(project.getIssueSetting().getUndefinedFieldValues());
undefinedFieldValues.addAll(project.getBuildSetting().getUndefinedFieldValues());
}
@@ -732,7 +740,7 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
}
}
- for (Project project: projectService.query()) {
+ for (Project project: getProjectsForWorkflowReconciliation()) {
project.getIssueSetting().fixUndefinedStates(resolutions);
project.getBuildSetting().fixUndefinedStates(resolutions);
}
@@ -783,7 +791,7 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
query.executeUpdate();
}
- for (Project project: projectService.query()) {
+ for (Project project: getProjectsForWorkflowReconciliation()) {
project.getIssueSetting().fixUndefinedFields(resolutions);
project.getBuildSetting().fixUndefinedFields(resolutions);
}
@@ -840,7 +848,7 @@ public class DefaultIssueService extends BaseEntityService<Issue> implements Iss
}
}
- for (Project project: projectService.query()) {
+ for (Project project: getProjectsForWorkflowReconciliation()) {
project.getIssueSetting().fixUndefinedFieldValues(resolutions);
project.getBuildSetting().fixUndefinedFieldValues(resolutions);
}
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultProjectService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultProjectService.java
index 7c1d1366a8..cad7028f05 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultProjectService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultProjectService.java
@@ -319,6 +319,7 @@ public class DefaultProjectService extends BaseEntityService<Project>
@Override
public void update(Project project) {
Preconditions.checkState(!project.isNew());
+ checkProjectParent(project);
String oldPath = project.getPath();
String newPath = project.calcPath();
if (!newPath.equals(oldPath)) {
@@ -351,6 +352,7 @@ public class DefaultProjectService extends BaseEntityService<Project>
@Override
public void create(User user, Project project) {
Preconditions.checkState(project.isNew());
+ checkProjectParent(project);
Project parent = project.getParent();
if (parent != null && parent.isNew()) {
create(user, parent);
@@ -400,7 +402,8 @@ public class DefaultProjectService extends BaseEntityService<Project>
public void on(EntityPersisted event) {
if (event.getEntity() instanceof Project) {
ProjectFacade facade = ((Project) event.getEntity()).getFacade();
- transactionService.runAfterCommit(() -> cache.put(facade.getId(), facade));
+ if (facade.getId() > 0)
+ transactionService.runAfterCommit(() -> cache.put(facade.getId(), facade));
}
}
@@ -543,6 +546,13 @@ public class DefaultProjectService extends BaseEntityService<Project>
return null;
}
+ private void checkProjectParent(Project project) {
+ for (var parent = project.getParent(); parent != null; parent = parent.getParent()) {
+ if (Project.DEFAULT_ID.equals(parent.getId()))
+ throw new ExplicitException("Project defaults cannot be used as a parent project");
+ }
+ }
+
@Sessional
@Override
public Project setup(Subject subject, String path) {
@@ -560,6 +570,8 @@ public class DefaultProjectService extends BaseEntityService<Project>
criteria.add(Restrictions.isNull(Project.PROP_PARENT));
criteria.add(Restrictions.eq(Project.PROP_NAME, name));
child = find(criteria);
+ if (child != null && Project.DEFAULT_ID.equals(child.getId()))
+ throw new ExplicitException("Project defaults cannot be used as an import target or parent project");
if (child == null) {
if (project == null && !SecurityUtils.canCreateRootProjects(subject))
throw new UnauthorizedException(_T("Not authorized to create root project"));
@@ -997,12 +1009,15 @@ public class DefaultProjectService extends BaseEntityService<Project>
@Override
public List<Project> query() {
- return query(true);
+ EntityCriteria<Project> criteria = newCriteria();
+ criteria.add(Restrictions.gt(Project.PROP_ID, 0L));
+ criteria.setCacheable(true);
+ return query(criteria);
}
@Override
public int count() {
- return count(true);
+ return cache.size();
}
private Order getOrder(EntitySort sort, CriteriaBuilder builder, From<Project, Project> root) {
@@ -1055,6 +1070,7 @@ public class DefaultProjectService extends BaseEntityService<Project>
private Predicate[] getPredicates(Subject subject, @Nullable Criteria<Project> criteria, CriteriaQuery<?> query,
From<Project, Project> from, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<>();
+ predicates.add(builder.gt(from.get(Project.PROP_ID), 0));
if (!SecurityUtils.isAdministrator(subject)) {
Collection<Project> projects = SecurityUtils.getAuthorizedProjects(subject, new AccessProject());
if (!projects.isEmpty()) {
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java
index ed97345cf2..cebcd74705 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java
@@ -89,6 +89,7 @@ import io.onedev.server.util.concurrent.Prioritized;
import io.onedev.server.util.facade.UserCache;
import io.onedev.server.util.facade.UserFacade;
import io.onedev.server.util.usage.Usage;
+import io.onedev.server.web.util.WicketUtils;
@Singleton
public class DefaultUserService extends BaseEntityService<User> implements UserService, Serializable {
@@ -185,7 +186,10 @@ public class DefaultUserService extends BaseEntityService<User> implements UserS
dao.persist(user);
if (oldName != null && !oldName.equals(user.getName())) {
- for (Project project: projectService.query()) {
+ var projects = new ArrayList<>(projectService.query());
+ if (WicketUtils.isSubscriptionActive())
+ projects.add(projectService.load(Project.DEFAULT_ID));
+ for (Project project: projects) {
try {
for (BranchProtection protection : project.getBranchProtections())
protection.onRenameUser(oldName, user.getName());
@@ -351,7 +355,10 @@ public class DefaultUserService extends BaseEntityService<User> implements UserS
private void checkUsage(User user) {
Usage usage = new Usage();
- for (Project project: projectService.query()) {
+ var projects = new ArrayList<>(projectService.query());
+ if (WicketUtils.isSubscriptionActive())
+ projects.add(projectService.load(Project.DEFAULT_ID));
+ for (Project project: projects) {
try {
Usage usageInProject = new Usage();
for (BranchProtection protection : project.getBranchProtections())
diff --git a/server-core/src/main/java/io/onedev/server/util/jackson/hibernate/ForeignKeyDeserializer.java b/server-core/src/main/java/io/onedev/server/util/jackson/hibernate/ForeignKeyDeserializer.java
index 3c6aa3dec4..e120bc4c6e 100644
--- a/server-core/src/main/java/io/onedev/server/util/jackson/hibernate/ForeignKeyDeserializer.java
+++ b/server-core/src/main/java/io/onedev/server/util/jackson/hibernate/ForeignKeyDeserializer.java
@@ -6,6 +6,12 @@ import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import io.onedev.commons.loader.AppLoader;
import io.onedev.server.model.AbstractEntity;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.UserAuthorization;
+import io.onedev.server.model.GroupAuthorization;
+import io.onedev.server.model.BaseAuthorization;
+import io.onedev.server.rest.RestProjectUtils;
import io.onedev.server.persistence.dao.Dao;
import java.io.IOException;
@@ -27,6 +33,16 @@ public final class ForeignKeyDeserializer extends StdDeserializer<AbstractEntity
JsonProcessingException {
Long entityId = jp.getLongValue();
Class<? extends AbstractEntity> valueClass = (Class<? extends AbstractEntity>) handledType();
+ if (valueClass == Project.class && entityId < 0) {
+ var owner = jp.currentValue();
+ if (Project.DEFAULT_ID.equals(entityId) && (owner instanceof UserAuthorization
+ || owner instanceof GroupAuthorization || owner instanceof BaseAuthorization
+ || owner instanceof AccessTokenAuthorization)) {
+ RestProjectUtils.checkProjectDefaultsPermission();
+ } else {
+ RestProjectUtils.checkProjectId(entityId);
+ }
+ }
return (AbstractEntity) AppLoader.getInstance(Dao.class).load(valueClass, entityId);
}
-}
\ No newline at end of file
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/commandpalette/CommandPalettePanel.java b/server-core/src/main/java/io/onedev/server/web/component/commandpalette/CommandPalettePanel.java
index f4c9fda89b..3f3a6a6222 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/commandpalette/CommandPalettePanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/commandpalette/CommandPalettePanel.java
@@ -192,7 +192,7 @@ public abstract class CommandPalettePanel extends Panel {
super.onInitialize();
var matcher = new PathMatcher();
- if (getPage() instanceof ProjectPage) {
+ if (getPage() instanceof ProjectPage && ((ProjectPage) getPage()).getProject().getId() > 0) {
for (String[] url: availableUrls) {
if (WicketUtils.isSubscriptionActive()
|| !eeUrlPatterns.matches(matcher, Joiner.on("/").join(url))) {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/project/choice/ProjectChoiceProvider.java b/server-core/src/main/java/io/onedev/server/web/component/project/choice/ProjectChoiceProvider.java
index 65d8159e5c..7ddb5dd0ae 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/project/choice/ProjectChoiceProvider.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/project/choice/ProjectChoiceProvider.java
@@ -74,6 +74,8 @@ public class ProjectChoiceProvider extends ChoiceProvider<Project> {
@Override
public double getSimilarScore(Project object) {
+ if (Project.DEFAULT_ID.equals(object.getId()))
+ return Similarities.getSimilarScore(object.getPath(), term);
return cache.getSimilarScore(object, term);
}
@@ -82,4 +84,4 @@ public class ProjectChoiceProvider extends ChoiceProvider<Project> {
new ResponseFiller<Project>(response).fill(similarities, page, WebConstants.PAGE_SIZE);
}
-}
\ No newline at end of file
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenAuthorizationBean.java b/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenAuthorizationBean.java
index f6594c85d2..96347e9c65 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenAuthorizationBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenAuthorizationBean.java
@@ -1,5 +1,6 @@
package io.onedev.server.web.component.user.accesstoken;
+import static io.onedev.server.web.translation.Translation._T;
import static java.util.Comparator.comparing;
import java.io.Serializable;
@@ -9,13 +10,20 @@ import java.util.List;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
+import org.apache.shiro.authz.UnauthorizedException;
+
+import io.onedev.server.OneDev;
import io.onedev.server.annotation.Editable;
import io.onedev.server.annotation.ProjectChoice;
import io.onedev.server.annotation.RoleChoice;
+import io.onedev.server.exception.NoSubscriptionException;
import io.onedev.server.model.Project;
+import io.onedev.server.model.User;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.security.permission.ManageProject;
+import io.onedev.server.service.ProjectService;
import io.onedev.server.util.HierarchicalContext;
+import io.onedev.server.web.util.WicketUtils;
import io.onedev.server.web.util.UserAware;
@Editable
@@ -27,7 +35,7 @@ public class AccessTokenAuthorizationBean implements Serializable {
private List<String> roleNames;
- @Editable(order=100, name="Project")
+ @Editable(order=100, name="Project", descriptionProvider="getProjectDescription")
@ProjectChoice("getManageableProjects")
@NotEmpty
public String getProjectPath() {
@@ -37,15 +45,43 @@ public class AccessTokenAuthorizationBean implements Serializable {
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
+
+ @SuppressWarnings("unused")
+ private static String getProjectDescription() {
+ var user = HierarchicalContext.get().findData(UserAware.class).getUser();
+ if (SecurityUtils.isAdministrator(user.asSubject()) && WicketUtils.isSubscriptionActive())
+ return _T("Select <code>~default</code> to apply the selected roles to all projects, including projects created later");
+ else
+ return "";
+ }
@SuppressWarnings("unused")
private static List<Project> getManageableProjects() {
var user = HierarchicalContext.get().findData(UserAware.class).getUser();
var projects = new ArrayList<>(SecurityUtils.getAuthorizedProjects(user.asSubject(), new ManageProject()));
projects.sort(comparing(Project::getPath));
+ if (SecurityUtils.isAdministrator(user.asSubject()) && WicketUtils.isSubscriptionActive())
+ projects.add(0, OneDev.getInstance(ProjectService.class).load(Project.DEFAULT_ID));
return projects;
}
+ public Project resolveProject(User owner) {
+ var projectService = OneDev.getInstance(ProjectService.class);
+ Project project;
+ if (Project.DEFAULT_NAME.equals(projectPath)) {
+ if (!SecurityUtils.isAdministrator(owner.asSubject()))
+ throw new UnauthorizedException();
+ if (!WicketUtils.isSubscriptionActive())
+ throw new NoSubscriptionException("Project defaults");
+ project = projectService.load(Project.DEFAULT_ID);
+ } else {
+ project = projectService.findByPath(projectPath);
+ }
+ if (project == null || !SecurityUtils.canManageProject(owner.asSubject(), project))
+ throw new UnauthorizedException("Access token owner should have permission to manage authorized project");
+ return project;
+ }
+
@Editable(order=200, name="Role")
@RoleChoice
@Size(min=1, message = "At least one role must be selected")
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenEditPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenEditPanel.java
index a2f23f9055..f99aeaf1c8 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenEditPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenEditPanel.java
@@ -19,15 +19,16 @@ import io.onedev.server.data.migration.VersionedXmlDoc;
import io.onedev.server.service.AccessTokenAuthorizationService;
import io.onedev.server.service.AccessTokenService;
import io.onedev.server.service.AuditService;
-import io.onedev.server.service.ProjectService;
import io.onedev.server.service.RoleService;
import io.onedev.server.model.AccessToken;
import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.Project;
import io.onedev.server.persistence.TransactionService;
import io.onedev.server.util.Path;
import io.onedev.server.util.PathNode;
import io.onedev.server.web.editable.BeanContext;
import io.onedev.server.web.page.user.UserPage;
+import io.onedev.server.web.util.WicketUtils;
abstract class AccessTokenEditPanel extends Panel {
@@ -48,6 +49,8 @@ abstract class AccessTokenEditPanel extends Panel {
if (!token.isNew())
oldAuditContent = VersionedXmlDoc.fromBean(bean).toXML();
+ if (!WicketUtils.isSubscriptionActive())
+ bean.getAuthorizations().removeIf(it -> Project.DEFAULT_NAME.equals(it.getProjectPath()));
var editor = BeanContext.edit("editor", bean, Sets.newHashSet("value"), true);
form.add(editor);
@@ -72,10 +75,6 @@ abstract class AccessTokenEditPanel extends Panel {
editor.error(new Path(new PathNode.Named("name")), _T("Name already used by another access token of the owner"));
target.add(AccessTokenEditPanel.this);
} else {
- token.setName(bean.getName());
- token.setValue(bean.getValue());
- token.setHasOwnerPermissions(bean.isHasOwnerPermissions());
-
var projectPaths = new HashSet<String>();
var authorizations = new ArrayList<AccessTokenAuthorization>();
for (var authorizationBean : bean.getAuthorizations()) {
@@ -84,7 +83,7 @@ abstract class AccessTokenEditPanel extends Panel {
target.add(AccessTokenEditPanel.this);
return;
} else {
- var project = getProjectService().findByPath(authorizationBean.getProjectPath());
+ var project = authorizationBean.resolveProject(token.getOwner());
authorizationBean.getRoleNames().forEach(it -> {
var authorization = new AccessTokenAuthorization();
authorization.setProject(project);
@@ -94,6 +93,9 @@ abstract class AccessTokenEditPanel extends Panel {
});
}
}
+ token.setName(bean.getName());
+ token.setValue(bean.getValue());
+ token.setHasOwnerPermissions(bean.isHasOwnerPermissions());
token.setExpireDate(bean.getExpireDate());
getTransactionService().run(() -> {
@@ -135,7 +137,7 @@ abstract class AccessTokenEditPanel extends Panel {
private AuditService getAuditService() {
return OneDev.getInstance(AuditService.class);
}
-
+
private TransactionService getTransactionService() {
return OneDev.getInstance(TransactionService.class);
}
@@ -152,10 +154,6 @@ abstract class AccessTokenEditPanel extends Panel {
return OneDev.getInstance(RoleService.class);
}
- private ProjectService getProjectService() {
- return OneDev.getInstance(ProjectService.class);
- }
-
protected abstract AccessToken getToken();
protected abstract void onSaved(AjaxRequestTarget target);
diff --git a/server-core/src/main/java/io/onedev/server/web/editable/EditableUtils.java b/server-core/src/main/java/io/onedev/server/web/editable/EditableUtils.java
index cd4223e1a1..5bca55f428 100644
--- a/server-core/src/main/java/io/onedev/server/web/editable/EditableUtils.java
+++ b/server-core/src/main/java/io/onedev/server/web/editable/EditableUtils.java
@@ -6,6 +6,7 @@ import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.List;
+import org.apache.wicket.Session;
import org.jspecify.annotations.Nullable;
import io.onedev.server.OneDev;
@@ -15,8 +16,10 @@ import io.onedev.server.annotation.WorkingPeriod;
import io.onedev.server.model.Project;
import io.onedev.server.service.SettingService;
import io.onedev.server.util.BeanUtils;
+import io.onedev.server.util.HtmlUtils;
import io.onedev.server.util.ReflectionUtils;
import io.onedev.server.util.interpolative.VariableInterpolator;
+import io.onedev.server.web.util.WicketUtils;
public class EditableUtils {
@@ -91,30 +94,10 @@ public class EditableUtils {
if (editable == null) {
return null;
} else if (element.getAnnotation(Interpolative.class) != null) {
- String description = getDescription(element, editable);
- if (description.length() != 0) {
- if (description.endsWith("<br>")) {
- description += VariableInterpolator.getHelp();
- } else {
- if (!description.endsWith("."))
- description += ".";
- description += " " + VariableInterpolator.getHelp();
- }
- } else {
- description = VariableInterpolator.getHelp();
- }
- return description;
+ return appendDescription(getDescription(element, editable), VariableInterpolator.getHelp());
} else if (element.getAnnotation(WorkingPeriod.class) != null) {
var timeTrackingSetting = OneDev.getInstance(SettingService.class).getIssueSetting().getTimeTrackingSetting();
- String description = getDescription(element, editable);
- if (description.length() != 0) {
- if (!description.endsWith("."))
- description += ".";
- description += " " + timeTrackingSetting.getWorkingPeriodHelp();
- } else {
- description = timeTrackingSetting.getWorkingPeriodHelp();
- }
- return description;
+ return appendDescription(getDescription(element, editable), timeTrackingSetting.getWorkingPeriodHelp());
} else {
String description = getDescription(element, editable);
if (description.length() != 0)
@@ -125,6 +108,39 @@ public class EditableUtils {
}
private static String getDescription(AnnotatedElement element, Editable editable) {
+ String description = getBaseDescription(element, editable);
+ if (editable.topPlaceholder().length() != 0 || editable.topPlaceholderProvider().length() != 0) {
+ Project project = Project.get();
+ String inheritanceDescription = null;
+ if (project != null && !Project.DEFAULT_ID.equals(project.getId())) {
+ if (project.getParent() != null) {
+ inheritanceDescription = _T("Leave empty to inherit from the parent project.");
+ } else if (WicketUtils.isSubscriptionActive()) {
+ inheritanceDescription = _T("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.");
+ }
+ }
+ if (inheritanceDescription != null)
+ description = appendDescription(description, inheritanceDescription);
+ }
+ return description;
+ }
+
+ private static String appendDescription(String description, String help) {
+ description = description.stripTrailing();
+ if (description.isEmpty())
+ return help;
+ if (description.matches("(?is).*<br\\s*/?>$"))
+ return description + help;
+ // Inspect rendered text so punctuation inside markup or HTML entities is recognized too.
+ var text = HtmlUtils.getText(description).stripTrailing();
+ if (!text.matches("(?s).*[.!?。!?…][\\p{Pe}\\p{Pf}\"']*$")) {
+ var language = Session.exists() ? Session.get().getLocale().getLanguage() : "en";
+ description += language.equals("zh") || language.equals("ja") ? "。" : ".";
+ }
+ return description + " " + help;
+ }
+
+ private static String getBaseDescription(AnnotatedElement element, Editable editable) {
String description = editable.description();
if (description.length() != 0) {
if (isTranslatable(element))
@@ -157,13 +173,17 @@ public class EditableUtils {
Editable editable = element.getAnnotation(Editable.class);
Project project = Project.get();
if (project != null && project.getParent() == null) {
- String placeholder = editable.rootPlaceholder();
+ if ((editable.topPlaceholder().length() != 0 || editable.topPlaceholderProvider().length() != 0)
+ && !Project.DEFAULT_ID.equals(project.getId()) && WicketUtils.isSubscriptionActive()) {
+ return _T("Use default setting");
+ }
+ String placeholder = editable.topPlaceholder();
if (placeholder.length() != 0) {
if (isTranslatable(element))
return _T(placeholder);
else
return placeholder;
- } else if (editable.rootPlaceholderProvider().length() != 0) {
+ } else if (editable.topPlaceholderProvider().length() != 0) {
Class<?> clazz;
if (element instanceof Class)
clazz = (Class<?>) element;
@@ -171,7 +191,7 @@ public class EditableUtils {
clazz = ((Method) element).getDeclaringClass();
else
throw new RuntimeException("Unexpected element type: " + element);
- return (String) ReflectionUtils.invokeStaticMethod(clazz, editable.rootPlaceholderProvider());
+ return (String) ReflectionUtils.invokeStaticMethod(clazz, editable.topPlaceholderProvider());
}
}
String placeholder = editable.placeholder();
diff --git a/server-core/src/main/java/io/onedev/server/web/editable/project/choice/ProjectSingleChoiceEditor.java b/server-core/src/main/java/io/onedev/server/web/editable/project/choice/ProjectSingleChoiceEditor.java
index 8d3841af08..bd9f85fdfb 100644
--- a/server-core/src/main/java/io/onedev/server/web/editable/project/choice/ProjectSingleChoiceEditor.java
+++ b/server-core/src/main/java/io/onedev/server/web/editable/project/choice/ProjectSingleChoiceEditor.java
@@ -15,6 +15,8 @@ import org.apache.wicket.util.convert.ConversionException;
import io.onedev.server.OneDev;
import io.onedev.server.service.ProjectService;
import io.onedev.server.model.Project;
+import io.onedev.server.util.ComponentHierarchical;
+import io.onedev.server.util.HierarchicalContext;
import io.onedev.server.util.ReflectionUtils;
import io.onedev.server.util.facade.ProjectCache;
import io.onedev.server.web.component.project.choice.ProjectSingleChoice;
@@ -31,8 +33,13 @@ public class ProjectSingleChoiceEditor extends PropertyEditor<String> {
protected List<Project> load() {
ProjectChoice projectChoice = descriptor.getPropertyGetter().getAnnotation(ProjectChoice.class);
if (projectChoice.value().length() != 0) {
- return (List<Project>) ReflectionUtils.invokeStaticMethod(
- descriptor.getPropertyGetter().getDeclaringClass(), projectChoice.value());
+ HierarchicalContext.push(new HierarchicalContext(new ComponentHierarchical(ProjectSingleChoiceEditor.this)));
+ try {
+ return (List<Project>) ReflectionUtils.invokeStaticMethod(
+ descriptor.getPropertyGetter().getDeclaringClass(), projectChoice.value());
+ } finally {
+ HierarchicalContext.pop();
+ }
} else {
ProjectCache cache = getProjectService().cloneCache();
List<Project> projects = new ArrayList<>(cache.getProjects());
@@ -59,9 +66,12 @@ public class ProjectSingleChoiceEditor extends PropertyEditor<String> {
super.onInitialize();
Project selection;
- if (getModelObject() != null)
+ if (getModelObject() != null) {
selection = getProjectService().findByPath(getModelObject());
- else
+ if (selection == null)
+ selection = choicesModel.getObject().stream()
+ .filter(it -> it.getPath().equals(getModelObject())).findFirst().orElse(null);
+ } else
selection = null;
input = new ProjectSingleChoice("input", Model.of(selection), choicesModel) {
diff --git a/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java b/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java
index 227dd12cdc..f906345e1f 100644
--- a/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java
+++ b/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java
@@ -327,6 +327,26 @@ public class BaseUrlMapper extends CompoundRequestMapper {
}
private void addAdministrationPages() {
+ add(new ProjectDefaultsMapper("general", GeneralProjectSettingPage.class));
+ add(new ProjectDefaultsMapper("user-authorizations", io.onedev.server.web.page.project.setting.authorization.UserAuthorizationsPage.class));
+ add(new ProjectDefaultsMapper("group-authorizations", io.onedev.server.web.page.project.setting.authorization.GroupAuthorizationsPage.class));
+ add(new ProjectDefaultsMapper("code/branch-protection", BranchProtectionsPage.class));
+ add(new ProjectDefaultsMapper("code/tag-protection", TagProtectionsPage.class));
+ add(new ProjectDefaultsMapper("code/indexing", CodeIndexingSettingPage.class));
+ add(new ProjectDefaultsMapper("pull-request", PullRequestSettingPage.class));
+ add(new ProjectDefaultsMapper("issue/branch-prefix", IssueBranchPrefixPage.class));
+ add(new ProjectDefaultsMapper("build/job-secrets", JobSecretsPage.class));
+ add(new ProjectDefaultsMapper("build/job-properties", JobPropertiesPage.class));
+ add(new ProjectDefaultsMapper("build/build-preserve-rules", BuildPreservationsPage.class));
+ add(new ProjectDefaultsMapper("build/default-fixed-issue-filters", DefaultFixedIssueFiltersPage.class));
+ add(new ProjectDefaultsMapper("cache-management", CacheManagementPage.class));
+ add(new ProjectDefaultsMapper("workspace-spec", WorkspaceSpecsPage.class));
+ add(new ProjectDefaultsMapper("wiki", WikiSettingPage.class));
+ add(new ProjectDefaultsMapper("web-hooks", WebHooksPage.class));
+ add(new ProjectDefaultsMapper("ai", ProjectAiSettingPage.class));
+ add(new ProjectDefaultsMapper("${" + ContributedProjectSettingPage.PARAM_SETTING + "}",
+ ContributedProjectSettingPage.class));
+
add(new BasePageMapper("~administration/settings/system", SystemSettingPage.class));
add(new BasePageMapper("~administration/settings/security", SecuritySettingPage.class));
add(new BasePageMapper("~administration/users", UserListPage.class));
diff --git a/server-core/src/main/java/io/onedev/server/web/mapper/ProjectDefaultsMapper.java b/server-core/src/main/java/io/onedev/server/web/mapper/ProjectDefaultsMapper.java
new file mode 100644
index 0000000000..5653c48a48
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/mapper/ProjectDefaultsMapper.java
@@ -0,0 +1,33 @@
+package io.onedev.server.web.mapper;
+
+import org.apache.wicket.request.Request;
+import org.apache.wicket.request.Url;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import io.onedev.server.model.Project;
+import io.onedev.server.web.page.project.setting.ProjectSettingPage;
+
+/** Mounts the existing project editors in the administration area. */
+public class ProjectDefaultsMapper extends BasePageMapper {
+
+ public ProjectDefaultsMapper(String path, Class<? extends ProjectSettingPage> pageClass) {
+ super("~administration/project-defaults/" + path, pageClass);
+ }
+
+ @Override
+ protected PageParameters extractPageParameters(Request request, Url url) {
+ var parameters = super.extractPageParameters(request, url);
+ if (parameters == null)
+ parameters = new PageParameters();
+ return parameters.set(ProjectMapperUtils.PARAM_PROJECT, Project.DEFAULT_NAME);
+ }
+
+ @Override
+ protected boolean setPlaceholders(PageParameters parameters, Url url) {
+ if (!Project.DEFAULT_NAME.equals(parameters.get(ProjectMapperUtils.PARAM_PROJECT).toOptionalString()))
+ return false;
+ parameters.remove(ProjectMapperUtils.PARAM_PROJECT);
+ return super.setPlaceholders(parameters, url);
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/mapper/ProjectPageMapper.java b/server-core/src/main/java/io/onedev/server/web/mapper/ProjectPageMapper.java
index f521f6b2d2..219d39caf8 100644
--- a/server-core/src/main/java/io/onedev/server/web/mapper/ProjectPageMapper.java
+++ b/server-core/src/main/java/io/onedev/server/web/mapper/ProjectPageMapper.java
@@ -7,6 +7,8 @@ import org.apache.wicket.request.mapper.info.PageComponentInfo;
import org.apache.wicket.request.mapper.parameter.IPageParametersEncoder;
import org.apache.wicket.request.mapper.parameter.PageParameters;
+import io.onedev.server.model.Project;
+
public class ProjectPageMapper extends BasePageMapper {
private final Class<? extends IRequestablePage> pageClass;
@@ -18,6 +20,8 @@ public class ProjectPageMapper extends BasePageMapper {
@Override
protected boolean setPlaceholders(PageParameters parameters, Url url) {
+ if (Project.DEFAULT_NAME.equals(parameters.get(ProjectMapperUtils.PARAM_PROJECT).toOptionalString()))
+ return false;
return ProjectMapperUtils.setPlaceholders(parameters, url, mountSegments, new PlaceholderProvider() {
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/groupmanagement/authorization/GroupAuthorizationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/groupmanagement/authorization/GroupAuthorizationsPage.java
index 396b377434..835d4f31e2 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/groupmanagement/authorization/GroupAuthorizationsPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/groupmanagement/authorization/GroupAuthorizationsPage.java
@@ -17,8 +17,9 @@ import org.apache.wicket.request.mapper.parameter.PageParameters;
import io.onedev.server.OneDev;
import io.onedev.server.data.migration.VersionedXmlDoc;
+import io.onedev.server.model.Project;
+import io.onedev.server.web.util.WicketUtils;
import io.onedev.server.service.GroupAuthorizationService;
-import io.onedev.server.service.ProjectService;
import io.onedev.server.service.RoleService;
import io.onedev.server.model.GroupAuthorization;
import io.onedev.server.web.editable.PropertyContext;
@@ -52,6 +53,8 @@ public class GroupAuthorizationsPage extends GroupPage {
authorizationsBean.getAuthorizations().add(authorizationBean);
}
oldAuditContent = VersionedXmlDoc.fromBean(authorizationsBean).toXML();
+ if (!WicketUtils.isSubscriptionActive())
+ authorizationsBean.getAuthorizations().removeIf(it -> Project.DEFAULT_NAME.equals(it.getProjectPath()));
Form<?> form = new Form<Void>("form") {
@@ -66,7 +69,7 @@ public class GroupAuthorizationsPage extends GroupPage {
error(MessageFormat.format(_T("Duplicate authorizations found: {0}"), authorizationBean.getProjectPath()));
return;
} else {
- var project = getProjectService().findByPath(authorizationBean.getProjectPath());
+ var project = authorizationBean.resolveProject();
authorizationBean.getRoleNames().stream().forEach(it -> {
GroupAuthorization authorization = new GroupAuthorization();
authorization.setGroup(getGroup());
@@ -94,9 +97,6 @@ public class GroupAuthorizationsPage extends GroupPage {
return OneDev.getInstance(RoleService.class);
}
- private ProjectService getProjectService() {
- return OneDev.getInstance(ProjectService.class);
- }
private GroupAuthorizationService getGroupAuthorizationService() {
return OneDev.getInstance(GroupAuthorizationService.class);
diff --git a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
index 6db7c4765c..916469e728 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
@@ -67,6 +67,9 @@ import io.onedev.commons.loader.AppLoader;
import io.onedev.server.OneDev;
import io.onedev.server.ServerConfig;
import io.onedev.server.SubscriptionService;
+import io.onedev.server.model.Project;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.web.page.project.setting.ProjectSettingMenu;
import io.onedev.server.cluster.ClusterService;
import io.onedev.server.model.Alert;
import io.onedev.server.model.User;
@@ -375,6 +378,12 @@ public abstract class LayoutPage extends BasePage {
ChatPreserveDaysPage.class, new PageParameters()));
administrationMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("AI Settings"), aiMenuItems));
+ if (isSubscriptionActive()) {
+ administrationMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Project Defaults"),
+ ProjectSettingMenu.getMenuItems(OneDev.getInstance(ProjectService.class).load(Project.DEFAULT_ID))));
+ } else {
+ administrationMenuItems.add(new SidebarMenuItem.SubscriptionRequired(null, _T("Project Defaults")));
+ }
administrationMenuItems.add(new SidebarMenuItem.Page(null, _T("Branding"),
BrandingSettingPage.class, new PageParameters()));
diff --git a/server-core/src/main/java/io/onedev/server/web/page/layout/SidebarMenuItem.java b/server-core/src/main/java/io/onedev/server/web/page/layout/SidebarMenuItem.java
index 9cbb63d55a..bb3a1bafbf 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/layout/SidebarMenuItem.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/layout/SidebarMenuItem.java
@@ -4,6 +4,9 @@ import com.google.common.collect.Lists;
import io.onedev.server.web.page.admin.pluginsettings.ContributedAdministrationSettingPage;
import io.onedev.server.web.page.project.setting.pluginsettings.ContributedProjectSettingPage;
import io.onedev.server.web.util.WicketUtils;
+import io.onedev.server.web.mapper.ProjectMapperUtils;
+import io.onedev.server.web.page.project.setting.ProjectSettingPage;
+import java.util.Objects;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.jspecify.annotations.Nullable;
@@ -70,7 +73,14 @@ public abstract class SidebarMenuItem implements Serializable {
@Override
public boolean isActive() {
- org.apache.wicket.Page currentPage = WicketUtils.getPage();
+ var currentPage = WicketUtils.getPage();
+ if (currentPage instanceof ProjectSettingPage
+ && ProjectSettingPage.class.isAssignableFrom(pageClass)
+ && !Objects.equals(
+ currentPage.getPageParameters().get(ProjectMapperUtils.PARAM_PROJECT).toOptionalString(),
+ pageParams.get(ProjectMapperUtils.PARAM_PROJECT).toOptionalString())) {
+ return false;
+ }
if (pageClass.isAssignableFrom(currentPage.getClass())) {
if (pageClass.isAssignableFrom(ContributedAdministrationSettingPage.class)
|| pageClass.isAssignableFrom(ContributedProjectSettingPage.class)) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/NewProjectPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/NewProjectPage.java
index 200b7ec20d..390a67643e 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/NewProjectPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/NewProjectPage.java
@@ -12,6 +12,8 @@ import static io.onedev.server.web.translation.Translation._T;
import java.util.Collection;
+import jakarta.persistence.EntityNotFoundException;
+
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.wicket.Component;
import org.apache.wicket.Session;
@@ -49,6 +51,8 @@ public class NewProjectPage extends LayoutPage {
public NewProjectPage(PageParameters params) {
super(params);
parentId = params.get(PARAM_PARENT).toOptionalLong();
+ if (parentId != null && parentId < 0)
+ throw new EntityNotFoundException("Project not found");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java
index 9e0d47c48a..386dffe606 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/ProjectPage.java
@@ -10,10 +10,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import jakarta.inject.Inject;
-import jakarta.persistence.EntityNotFoundException;
-
import org.apache.commons.lang3.StringUtils;
+import org.apache.shiro.authz.UnauthorizedException;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.RestartResponseException;
@@ -29,7 +27,6 @@ import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
-import io.onedev.server.web.component.RepeatingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
@@ -52,11 +49,11 @@ import io.onedev.server.web.WebConstants;
import io.onedev.server.web.asset.dropdowntriangleindicator.DropdownTriangleIndicatorCssResourceReference;
import io.onedev.server.web.avatar.AvatarService;
import io.onedev.server.web.behavior.infinitescroll.InfiniteScrollBehavior;
+import io.onedev.server.web.component.RepeatingView;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.project.ProjectAvatar;
import io.onedev.server.web.component.project.childrentree.ProjectChildrenTree;
-import io.onedev.server.web.editable.EditableUtils;
import io.onedev.server.web.mapper.ProjectMapperUtils;
import io.onedev.server.web.opengraph.OpenGraphHeaderMeta;
import io.onedev.server.web.opengraph.OpenGraphHeaderMetaType;
@@ -64,8 +61,6 @@ import io.onedev.server.web.page.layout.LayoutPage;
import io.onedev.server.web.page.layout.SidebarMenu;
import io.onedev.server.web.page.layout.SidebarMenuItem;
import io.onedev.server.web.page.project.blob.ProjectBlobPage;
-import io.onedev.server.web.page.project.wiki.ProjectWikiPage;
-import io.onedev.server.web.page.project.setting.wiki.WikiSettingPage;
import io.onedev.server.web.page.project.branches.ProjectBranchesPage;
import io.onedev.server.web.page.project.builds.ProjectBuildsPage;
import io.onedev.server.web.page.project.builds.detail.BuildDetailPage;
@@ -89,35 +84,17 @@ import io.onedev.server.web.page.project.pullrequests.InvalidPullRequestPage;
import io.onedev.server.web.page.project.pullrequests.ProjectPullRequestsPage;
import io.onedev.server.web.page.project.pullrequests.create.NewPullRequestPage;
import io.onedev.server.web.page.project.pullrequests.detail.PullRequestDetailPage;
-import io.onedev.server.web.page.project.setting.ContributedProjectSetting;
-import io.onedev.server.web.page.project.setting.ProjectSettingContribution;
+import io.onedev.server.web.page.project.setting.ProjectSettingMenu;
import io.onedev.server.web.page.project.setting.ProjectSettingPage;
-import io.onedev.server.web.page.project.setting.ai.ProjectAiSettingPage;
-import io.onedev.server.web.page.project.setting.authorization.GroupAuthorizationsPage;
-import io.onedev.server.web.page.project.setting.authorization.UserAuthorizationsPage;
-import io.onedev.server.web.page.project.setting.avatar.AvatarEditPage;
-import io.onedev.server.web.page.project.setting.build.BuildPreservationsPage;
-import io.onedev.server.web.page.project.setting.build.DefaultFixedIssueFiltersPage;
-import io.onedev.server.web.page.project.setting.build.JobPropertiesPage;
-import io.onedev.server.web.page.project.setting.build.JobSecretsPage;
-import io.onedev.server.web.page.project.setting.cache.CacheManagementPage;
-import io.onedev.server.web.page.project.setting.code.analysis.CodeIndexingSettingPage;
-import io.onedev.server.web.page.project.setting.code.branchprotection.BranchProtectionsPage;
-import io.onedev.server.web.page.project.setting.code.git.GitPackConfigPage;
-import io.onedev.server.web.page.project.setting.code.pullrequest.PullRequestSettingPage;
-import io.onedev.server.web.page.project.setting.code.tagprotection.TagProtectionsPage;
-import io.onedev.server.web.page.project.setting.general.GeneralProjectSettingPage;
-import io.onedev.server.web.page.project.setting.issuesetting.IssueBranchPrefixPage;
-import io.onedev.server.web.page.project.setting.pluginsettings.ContributedProjectSettingPage;
-import io.onedev.server.web.page.project.setting.servicedesk.ServiceDeskSettingPage;
-import io.onedev.server.web.page.project.setting.webhook.WebHooksPage;
-import io.onedev.server.web.page.project.setting.workspacespec.WorkspaceSpecsPage;
import io.onedev.server.web.page.project.stats.code.CodeContribsPage;
import io.onedev.server.web.page.project.tags.ProjectTagsPage;
+import io.onedev.server.web.page.project.wiki.ProjectWikiPage;
import io.onedev.server.web.page.project.workspaces.ProjectWorkspacesPage;
import io.onedev.server.web.page.project.workspaces.detail.WorkspaceDetailPage;
import io.onedev.server.web.page.security.LoginPage;
import io.onedev.server.web.util.ProjectAware;
+import jakarta.inject.Inject;
+import jakarta.persistence.EntityNotFoundException;
public abstract class ProjectPage extends LayoutPage implements ProjectAware, ChatToolAware {
@@ -135,7 +112,16 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
projectPath = StringUtils.strip(projectPath, "/");
- Project project = getProjectService().findByPath(projectPath);
+ Project project;
+ if (Project.DEFAULT_NAME.equals(projectPath)) {
+ if (!(this instanceof ProjectSettingPage))
+ throw new IllegalStateException();
+ if (!SecurityUtils.isAdministrator())
+ throw new UnauthorizedException();
+ project = getProjectService().load(Project.DEFAULT_ID);
+ } else {
+ project = getProjectService().findByPath(projectPath);
+ }
if (project == null || !SecurityUtils.canAccessProject(project)) {
if (getLoginUser() != null)
throw new EntityNotFoundException("Project not found or inaccessible");
@@ -175,12 +161,7 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
protected Map<String, ObjectId> getObjectIdCache() {
return new HashMap<>();
}
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- }
-
+
@Override
public Project getProject() {
return projectModel.getObject();
@@ -188,6 +169,8 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
@Override
protected List<SidebarMenu> getSidebarMenus() {
+ if (Project.DEFAULT_ID.equals(getProject().getId()))
+ return super.getSidebarMenus();
List<SidebarMenuItem> menuItems = new ArrayList<>();
menuItems.add(new SidebarMenuItem.Page("dashboard", _T("Overview"),
@@ -270,102 +253,12 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
menuItems.add(new SidebarMenuItem.SubMenu("stats", _T("Statistics"), statsMenuItems));
if (SecurityUtils.canManageProject(getProject())) {
- List<SidebarMenuItem> settingMenuItems = new ArrayList<>();
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("General"),
- GeneralProjectSettingPage.class, GeneralProjectSettingPage.paramsOf(getProject())));
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Edit Avatar"),
- AvatarEditPage.class, AvatarEditPage.paramsOf(getProject())));
-
- List<SidebarMenuItem> authorizationMenuItems = new ArrayList<>();
- authorizationMenuItems.add(new SidebarMenuItem.Page(null, _T("By User"),
- UserAuthorizationsPage.class, UserAuthorizationsPage.paramsOf(getProject())));
- authorizationMenuItems.add(new SidebarMenuItem.Page(null, _T("By Group"),
- GroupAuthorizationsPage.class, GroupAuthorizationsPage.paramsOf(getProject())));
- settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Authorization"), authorizationMenuItems));
-
- List<SidebarMenuItem> codeSettingMenuItems = new ArrayList<>();
- codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Branch Protection"),
- BranchProtectionsPage.class, BranchProtectionsPage.paramsOf(getProject())));
- codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Tag Protection"),
- TagProtectionsPage.class, TagProtectionsPage.paramsOf(getProject())));
- codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Code Indexing"),
- CodeIndexingSettingPage.class, CodeIndexingSettingPage.paramsOf(getProject())));
- if (getProject().isCodeManagement()) {
- codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Git Pack Config"),
- GitPackConfigPage.class, GitPackConfigPage.paramsOf(getProject())));
- }
-
- settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Code"), codeSettingMenuItems));
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Pull Request"),
- PullRequestSettingPage.class, PullRequestSettingPage.paramsOf(getProject())));
-
- if (getProject().isIssueManagement()) {
- List<SidebarMenuItem> issueSettingMenuItems = new ArrayList<>();
- issueSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Branch Prefix"),
- IssueBranchPrefixPage.class, IssueBranchPrefixPage.paramsOf(getProject())));
- settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Issue"), issueSettingMenuItems));
- }
-
- List<SidebarMenuItem> buildSettingMenuItems = new ArrayList<>();
-
- buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Job Secrets"),
- JobSecretsPage.class, JobSecretsPage.paramsOf(getProject())));
- buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Job Properties"),
- JobPropertiesPage.class, JobPropertiesPage.paramsOf(getProject())));
- buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Build Preserve Rules"),
- BuildPreservationsPage.class, BuildPreservationsPage.paramsOf(getProject())));
- buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Default Fixed Issue Filters"),
- DefaultFixedIssueFiltersPage.class, DefaultFixedIssueFiltersPage.paramsOf(getProject())));
-
- settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Build"), buildSettingMenuItems));
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Workspace Specs"),
- WorkspaceSpecsPage.class, WorkspaceSpecsPage.paramsOf(getProject())));
-
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Cache Management"),
- CacheManagementPage.class, CacheManagementPage.paramsOf(getProject())));
-
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Wiki"),
- WikiSettingPage.class, WikiSettingPage.paramsOf(getProject())));
-
- if (getSettingService().getServiceDeskSetting() != null && getProject().isIssueManagement()) {
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Service Desk"),
- ServiceDeskSettingPage.class, ServiceDeskSettingPage.paramsOf(getProject())));
- }
-
- SidebarMenuItem webHooksItem = new SidebarMenuItem.Page(null, _T("Web Hooks"),
- WebHooksPage.class, WebHooksPage.paramsOf(getProject()));
- settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Notification"), Lists.newArrayList(webHooksItem)));
-
- settingMenuItems.add(new SidebarMenuItem.Page(null, _T("AI"),
- ProjectAiSettingPage.class, ProjectAiSettingPage.paramsOf(getProject())));
-
- menuItems.add(new SidebarMenuItem.SubMenu("sliders", _T("Settings"), settingMenuItems));
+ menuItems.add(new SidebarMenuItem.SubMenu("sliders", _T("Settings"),
+ ProjectSettingMenu.getMenuItems(getProject())));
}
-
+
String avatarUrl = OneDev.getInstance(AvatarService.class).getProjectAvatarUrl(getProject().getId());
var menu = new SidebarMenu(new SidebarMenu.Header(avatarUrl, getProject().getName()), menuItems);
-
- if (SecurityUtils.canManageProject(getProject())) {
- List<Class<? extends ContributedProjectSetting>> contributedSettingClasses = new ArrayList<>();
- for (ProjectSettingContribution contribution:OneDev.getExtensions(ProjectSettingContribution.class)) {
- for (Class<? extends ContributedProjectSetting> settingClass: contribution.getSettingClasses())
- contributedSettingClasses.add(settingClass);
- }
- contributedSettingClasses.sort(Comparator.comparingInt(EditableUtils::getOrder));
-
- for (var contributedSettingClass: contributedSettingClasses) {
- var menuItem = new SidebarMenuItem.Page(
- null,
- _T(EditableUtils.getDisplayName(contributedSettingClass)),
- ContributedProjectSettingPage.class,
- ContributedProjectSettingPage.paramsOf(getProject(), contributedSettingClass));
- var group = EditableUtils.getGroup(contributedSettingClass);
- if (group != null)
- menu.insertMenuItem(new SidebarMenuItem.SubMenu("sliders", _T("Settings"), Lists.newArrayList(new SidebarMenuItem.SubMenu(null, _T(group), Lists.newArrayList(menuItem)))));
- else
- menu.insertMenuItem(new SidebarMenuItem.SubMenu("sliders", _T("Settings"), Lists.newArrayList(menuItem)));
- }
- }
var contributions = new ArrayList<>(OneDev.getExtensions(ProjectMenuContribution.class));
contributions.sort(Comparator.comparing(ProjectMenuContribution::getOrder));
@@ -523,6 +416,9 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
+ if (Project.DEFAULT_ID.equals(getProject().getId()))
+ return;
+
String description = getProject().getDescription();
if(description == null || description.equals("")) {
description = getProject().getName();
@@ -557,6 +453,8 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
@Override
public List<ChatTool> getChatTools() {
+ if (Project.DEFAULT_ID.equals(getProject().getId()))
+ return Collections.emptyList();
var tools = new ArrayList<ChatTool>();
if (getProject().isIssueManagement())
tools.add(wrapForChat(new CreateIssue(getProject().getId())));
@@ -564,6 +462,8 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
}
public static PageParameters paramsOf(Long projectId) {
+ if (Project.DEFAULT_ID.equals(projectId))
+ return paramsOf(Project.DEFAULT_NAME);
ProjectFacade project = getProjectService().findFacadeById(projectId);
return paramsOf(project.getPath());
}
@@ -575,7 +475,7 @@ public abstract class ProjectPage extends LayoutPage implements ProjectAware, Ch
}
public static PageParameters paramsOf(Project project) {
- return paramsOf(project.getPath());
+ return Project.DEFAULT_ID.equals(project.getId()) ? paramsOf(Project.DEFAULT_NAME) : paramsOf(project.getPath());
}
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingMenu.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingMenu.java
new file mode 100644
index 0000000000..c71404211e
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingMenu.java
@@ -0,0 +1,136 @@
+package io.onedev.server.web.page.project.setting;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+import com.google.common.collect.Lists;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.model.Project;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.web.editable.EditableUtils;
+import io.onedev.server.web.page.layout.SidebarMenu;
+import io.onedev.server.web.page.layout.SidebarMenuItem;
+import io.onedev.server.web.page.project.setting.ai.ProjectAiSettingPage;
+import io.onedev.server.web.page.project.setting.authorization.GroupAuthorizationsPage;
+import io.onedev.server.web.page.project.setting.authorization.UserAuthorizationsPage;
+import io.onedev.server.web.page.project.setting.avatar.AvatarEditPage;
+import io.onedev.server.web.page.project.setting.build.BuildPreservationsPage;
+import io.onedev.server.web.page.project.setting.build.DefaultFixedIssueFiltersPage;
+import io.onedev.server.web.page.project.setting.build.JobPropertiesPage;
+import io.onedev.server.web.page.project.setting.build.JobSecretsPage;
+import io.onedev.server.web.page.project.setting.cache.CacheManagementPage;
+import io.onedev.server.web.page.project.setting.code.analysis.CodeIndexingSettingPage;
+import io.onedev.server.web.page.project.setting.code.branchprotection.BranchProtectionsPage;
+import io.onedev.server.web.page.project.setting.code.git.GitPackConfigPage;
+import io.onedev.server.web.page.project.setting.code.pullrequest.PullRequestSettingPage;
+import io.onedev.server.web.page.project.setting.code.tagprotection.TagProtectionsPage;
+import io.onedev.server.web.page.project.setting.general.GeneralProjectSettingPage;
+import io.onedev.server.web.page.project.setting.issuesetting.IssueBranchPrefixPage;
+import io.onedev.server.web.page.project.setting.pluginsettings.ContributedProjectSettingPage;
+import io.onedev.server.web.page.project.setting.servicedesk.ServiceDeskSettingPage;
+import io.onedev.server.web.page.project.setting.webhook.WebHooksPage;
+import io.onedev.server.web.page.project.setting.wiki.WikiSettingPage;
+import io.onedev.server.web.page.project.setting.workspacespec.WorkspaceSpecsPage;
+
+public class ProjectSettingMenu {
+
+ public static List<SidebarMenuItem> getMenuItems(Project project) {
+ boolean defaults = Project.DEFAULT_ID.equals(project.getId());
+ List<SidebarMenuItem> settingMenuItems = new ArrayList<>();
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("General"),
+ GeneralProjectSettingPage.class, GeneralProjectSettingPage.paramsOf(project)));
+ if (!defaults) {
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Edit Avatar"),
+ AvatarEditPage.class, AvatarEditPage.paramsOf(project)));
+ }
+
+ List<SidebarMenuItem> authorizationMenuItems = new ArrayList<>();
+ authorizationMenuItems.add(new SidebarMenuItem.Page(null, _T("By User"),
+ UserAuthorizationsPage.class, UserAuthorizationsPage.paramsOf(project)));
+ authorizationMenuItems.add(new SidebarMenuItem.Page(null, _T("By Group"),
+ GroupAuthorizationsPage.class, GroupAuthorizationsPage.paramsOf(project)));
+ settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Authorization"), authorizationMenuItems));
+
+ List<SidebarMenuItem> codeSettingMenuItems = new ArrayList<>();
+ codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Branch Protection"),
+ BranchProtectionsPage.class, BranchProtectionsPage.paramsOf(project)));
+ codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Tag Protection"),
+ TagProtectionsPage.class, TagProtectionsPage.paramsOf(project)));
+ codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Code Indexing"),
+ CodeIndexingSettingPage.class, CodeIndexingSettingPage.paramsOf(project)));
+ if (!defaults && project.isCodeManagement()) {
+ codeSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Git Pack Config"),
+ GitPackConfigPage.class, GitPackConfigPage.paramsOf(project)));
+ }
+
+ settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Code"), codeSettingMenuItems));
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Pull Request"),
+ PullRequestSettingPage.class, PullRequestSettingPage.paramsOf(project)));
+
+ if (defaults || project.isIssueManagement()) {
+ List<SidebarMenuItem> issueSettingMenuItems = new ArrayList<>();
+ issueSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Branch Prefix"),
+ IssueBranchPrefixPage.class, IssueBranchPrefixPage.paramsOf(project)));
+ settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Issue"), issueSettingMenuItems));
+ }
+
+ List<SidebarMenuItem> buildSettingMenuItems = new ArrayList<>();
+
+ buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Job Secrets"),
+ JobSecretsPage.class, JobSecretsPage.paramsOf(project)));
+ buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Job Properties"),
+ JobPropertiesPage.class, JobPropertiesPage.paramsOf(project)));
+ buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Build Preserve Rules"),
+ BuildPreservationsPage.class, BuildPreservationsPage.paramsOf(project)));
+ buildSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Default Fixed Issue Filters"),
+ DefaultFixedIssueFiltersPage.class, DefaultFixedIssueFiltersPage.paramsOf(project)));
+
+ settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Build"), buildSettingMenuItems));
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Workspace Specs"),
+ WorkspaceSpecsPage.class, WorkspaceSpecsPage.paramsOf(project)));
+
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Cache Management"),
+ CacheManagementPage.class, CacheManagementPage.paramsOf(project)));
+
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Wiki"),
+ WikiSettingPage.class, WikiSettingPage.paramsOf(project)));
+
+ if (!defaults && OneDev.getInstance(SettingService.class).getServiceDeskSetting() != null && project.isIssueManagement()) {
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("Service Desk"),
+ ServiceDeskSettingPage.class, ServiceDeskSettingPage.paramsOf(project)));
+ }
+
+ SidebarMenuItem webHooksItem = new SidebarMenuItem.Page(null, _T("Web Hooks"),
+ WebHooksPage.class, WebHooksPage.paramsOf(project));
+ settingMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Notification"), Lists.newArrayList(webHooksItem)));
+
+ settingMenuItems.add(new SidebarMenuItem.Page(null, _T("AI"),
+ ProjectAiSettingPage.class, ProjectAiSettingPage.paramsOf(project)));
+
+ var menu = new SidebarMenu(null, settingMenuItems);
+ List<Class<? extends ContributedProjectSetting>> contributedSettingClasses = new ArrayList<>();
+ for (ProjectSettingContribution contribution:OneDev.getExtensions(ProjectSettingContribution.class)) {
+ for (Class<? extends ContributedProjectSetting> settingClass: contribution.getSettingClasses())
+ contributedSettingClasses.add(settingClass);
+ }
+ contributedSettingClasses.sort(Comparator.comparingInt(EditableUtils::getOrder));
+
+ for (var contributedSettingClass: contributedSettingClasses) {
+ var menuItem = new SidebarMenuItem.Page(
+ null,
+ _T(EditableUtils.getDisplayName(contributedSettingClass)),
+ ContributedProjectSettingPage.class,
+ ContributedProjectSettingPage.paramsOf(project, contributedSettingClass));
+ var group = EditableUtils.getGroup(contributedSettingClass);
+ if (group != null)
+ menu.insertMenuItem(new SidebarMenuItem.SubMenu(null, _T(group), Lists.newArrayList(menuItem)));
+ else
+ menu.insertMenuItem(menuItem);
+ }
+ return menu.getMenuItems();
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.html
index 4eb979fdef..3ce16dbf2c 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.html
@@ -2,4 +2,16 @@
<div class="project-setting p-2 p-sm-5">
<wicket:child></wicket:child>
</div>
-</wicket:extend>
\ No newline at end of file
+ <wicket:fragment wicket:id="defaultsTitleFrag">
+ <span wicket:id="defaults"></span>
+ <span class="dot"></span>
+ <span wicket:id="setting"></span>
+ </wicket:fragment>
+ <wicket:fragment wicket:id="projectTitleWithDefaultsHintFrag">
+ <wicket:container wicket:id="title"></wicket:container>
+ <span wicket:id="defaultsHint" class="project-defaults-hint ml-2 text-muted d-inline-flex flex-shrink-0" tabindex="0"
+ t:aria-label="Project Defaults" t:data-tippy-content="All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.">
+ <wicket:svg href="info-circle" class="icon icon-sm"/>
+ </span>
+ </wicket:fragment>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.java
index 29745e1cc1..04106c57dc 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/ProjectSettingPage.java
@@ -1,27 +1,65 @@
package io.onedev.server.web.page.project.setting;
-import io.onedev.server.web.component.link.ViewStateAwarePageLink;
+import static io.onedev.server.web.translation.Translation._T;
+
+import org.apache.wicket.Component;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.request.mapper.parameter.PageParameters;
+import io.onedev.server.exception.NoSubscriptionException;
import io.onedev.server.model.Project;
import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.web.component.link.ViewStateAwarePageLink;
+import io.onedev.server.web.page.admin.AdministrationCssResourceReference;
import io.onedev.server.web.page.project.ProjectPage;
import io.onedev.server.web.page.project.overview.ProjectOverviewPage;
+import io.onedev.server.web.util.WicketUtils;
public abstract class ProjectSettingPage extends ProjectPage {
public ProjectSettingPage(PageParameters params) {
super(params);
+
+ if (isProjectDefaults() && !WicketUtils.isSubscriptionActive())
+ throw new NoSubscriptionException("Project defaults");
}
@Override
protected boolean isPermitted() {
- return SecurityUtils.canManageProject(getProject());
+ if (isProjectDefaults())
+ return SecurityUtils.isAdministrator();
+ else
+ return SecurityUtils.canManageProject(getProject());
}
+ protected boolean isProjectDefaults() {
+ return Project.DEFAULT_ID.equals(getProject().getId());
+ }
+
+ protected boolean hasProjectDefaults() {
+ return true;
+ }
+
+ @Override
+ protected Component newTopbarTitle(String componentId) {
+ if (isProjectDefaults()) {
+ var fragment = new Fragment(componentId, "defaultsTitleFrag", this);
+ fragment.add(new Label("defaults", _T("Project Defaults")));
+ fragment.add(newProjectTitle("setting"));
+ return fragment;
+ }
+ var fragment = new Fragment(componentId, "projectTitleWithDefaultsHintFrag", this);
+ fragment.add(super.newTopbarTitle("title").setRenderBodyOnly(true));
+ fragment.add(new WebMarkupContainer("defaultsHint")
+ .setVisible(hasProjectDefaults() && getProject().getParent() == null && !WicketUtils.isSubscriptionActive()));
+ return fragment;
+ }
+
@Override
protected BookmarkablePageLink<Void> navToProject(String componentId, Project project) {
if (SecurityUtils.canManageProject(project))
@@ -35,11 +73,13 @@ public abstract class ProjectSettingPage extends ProjectPage {
super.renderHead(response);
response.render(CssHeaderItem.forReference(new ProjectSettingResourceReference()));
+ if (isProjectDefaults())
+ response.render(CssHeaderItem.forReference(new AdministrationCssResourceReference()));
}
@Override
protected String getPageTitle() {
- return "Settings - " + getProject().getPath();
+ return isProjectDefaults() ? "Project Defaults - Administration" : "Settings - " + getProject().getPath();
}
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/GroupAuthorizationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/GroupAuthorizationsPage.java
index fc1fa22a4a..aa18647408 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/GroupAuthorizationsPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/GroupAuthorizationsPage.java
@@ -64,8 +64,8 @@ public class GroupAuthorizationsPage extends ProjectSettingPage {
SecurityUtils.checkPermission(new ProjectPermission(getProject(), new ManageProject()));
- if (getProject().getParent() == null
- || !SecurityUtils.canManageProject(getProject().getParent())) {
+ var settingsParent = getProject().getSettingsParent();
+ if (settingsParent == null || !SecurityUtils.canManageProject(settingsParent)) {
boolean canManageProject = false;
Project project = getProject();
User user = SecurityUtils.getAuthUser();
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/UserAuthorizationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/UserAuthorizationsPage.java
index 0d110beab3..2105ca9c79 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/UserAuthorizationsPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/authorization/UserAuthorizationsPage.java
@@ -66,8 +66,8 @@ public class UserAuthorizationsPage extends ProjectSettingPage {
SecurityUtils.checkPermission(new ProjectPermission(getProject(), new ManageProject()));
- if (getProject().getParent() == null
- || !SecurityUtils.canManageProject(getProject().getParent())) {
+ var settingsParent = getProject().getSettingsParent();
+ if (settingsParent == null || !SecurityUtils.canManageProject(settingsParent)) {
boolean canManageProject = false;
Project project = getProject();
User user = SecurityUtils.getAuthUser();
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/avatar/AvatarEditPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/avatar/AvatarEditPage.java
index 88f6859a36..657f04c58f 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/avatar/AvatarEditPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/avatar/AvatarEditPage.java
@@ -85,6 +85,11 @@ public class AvatarEditPage extends ProjectSettingPage {
add(form);
}
+ @Override
+ protected boolean hasProjectDefaults() {
+ return false;
+ }
+
@Override
protected Component newProjectTitle(String componentId) {
return new Label(componentId, _T("Edit Avatar")).add(AttributeAppender.replace("class", "text-truncate"));
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/build/CacheSettingBean.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/build/CacheSettingBean.java
index 39fd07e976..d706ddcb30 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/build/CacheSettingBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/build/CacheSettingBean.java
@@ -13,7 +13,7 @@ public class CacheSettingBean implements Serializable {
private Integer preserveDays;
- @Editable(placeholder = "Inherit from parent", rootPlaceholder = ProjectBuildSetting.DEFAULT_CACHE_PRESERVE_DAYS + " days",
+ @Editable(placeholder = "Inherit from parent", topPlaceholder = ProjectBuildSetting.DEFAULT_CACHE_PRESERVE_DAYS + " days",
description = "Cache will be deleted to save space if not accessed for this number of days")
@OmitName
@Min(1)
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.html
index a473823336..c30b1c15bb 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.html
@@ -8,7 +8,7 @@
</form>
</div>
</div>
- <div class="card">
+ <div wicket:id="uploadedCaches" class="card">
<div class="card-body">
<h6 class="mb-4"><wicket:t>Uploaded Caches</wicket:t></h6>
<table wicket:id="caches" class="table table-hover"></table>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java
index 662715f53a..dc7e66861f 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/cache/CacheManagementPage.java
@@ -18,6 +18,7 @@ import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.repeater.Item;
@@ -164,7 +165,7 @@ public class CacheManagementPage extends ProjectSettingPage {
SortableDataProvider<RunCacheInfo, Void> dataProvider = new SortableDataProvider<>() {
private List<RunCacheInfo> listCaches() {
- return getCacheService().listCaches(getProject().getId());
+ return isProjectDefaults() ? List.of() : getCacheService().listCaches(getProject().getId());
}
@Override
@@ -203,8 +204,11 @@ public class CacheManagementPage extends ProjectSettingPage {
};
- add(cachesTable = new DefaultDataTable<>("caches", columns, dataProvider,
+ var uploadedCaches = new WebMarkupContainer("uploadedCaches");
+ uploadedCaches.setVisible(!isProjectDefaults());
+ uploadedCaches.add(cachesTable = new DefaultDataTable<>("caches", columns, dataProvider,
WebConstants.PAGE_SIZE, pagingHistorySupport));
+ add(uploadedCaches);
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/code/git/GitPackConfigPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/code/git/GitPackConfigPage.java
index 1d725fb7a3..8d6a0ef9b4 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/code/git/GitPackConfigPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/code/git/GitPackConfigPage.java
@@ -9,6 +9,8 @@ import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.request.mapper.parameter.PageParameters;
+import jakarta.persistence.EntityNotFoundException;
+
import io.onedev.server.OneDev;
import io.onedev.server.cluster.ClusterService;
import io.onedev.server.cluster.ClusterTask;
@@ -27,6 +29,8 @@ public class GitPackConfigPage extends ProjectSettingPage {
public GitPackConfigPage(PageParameters params) {
super(params);
+ if (isProjectDefaults())
+ throw new EntityNotFoundException("Project not found");
}
@Override
@@ -73,6 +77,11 @@ public class GitPackConfigPage extends ProjectSettingPage {
add(form);
}
+ @Override
+ protected boolean hasProjectDefaults() {
+ return false;
+ }
+
@Override
protected Component newProjectTitle(String componentId) {
return new Label(componentId, "<span class='text-truncate'>" + _T("Git Pack Config") + "</span>").setEscapeModelStrings(false);
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/DefaultRolesBean.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/DefaultRolesBean.java
index 061c57251d..c095b2bcb7 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/DefaultRolesBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/DefaultRolesBean.java
@@ -19,7 +19,7 @@ public class DefaultRolesBean implements Serializable {
private List<String> roleNames = new ArrayList<>();
- @Editable(name="Default Roles", placeholder="Inherit from parent", rootPlaceholder ="No default roles", description="Default roles affect default " +
+ @Editable(name="Default Roles", placeholder="Inherit from parent", topPlaceholder ="No default roles", description="Default roles affect default " +
"permissions granted to everyone in the system. The actual default permissions will be <b class='text-warning'>all permissions</b> contained in default roles of this " +
"project and all its parent projects")
@RoleChoice
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/GeneralProjectSettingPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/GeneralProjectSettingPage.java
index 0350cf024a..85059a5518 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/GeneralProjectSettingPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/general/GeneralProjectSettingPage.java
@@ -20,6 +20,7 @@ import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
@@ -59,13 +60,17 @@ public class GeneralProjectSettingPage extends ProjectSettingPage {
protected void onInitialize() {
super.onInitialize();
+ DefaultRolesBean defaultRolesBean = new DefaultRolesBean();
+ defaultRolesBean.setRoles(getProject().getBaseAuthorizations().stream().map(it->it.getRole()).collect(Collectors.toList()));
+ if (isProjectDefaults()) {
+ add(newDefaultsForm(defaultRolesBean));
+ return;
+ }
+
Collection<String> properties = Sets.newHashSet(PROP_NAME, PROP_KEY,
PROP_DESCRIPTION, PROP_CODE_MANAGEMENT, PROP_WIKI_MANAGEMENT, PROP_PACK_MANAGEMENT,
PROP_ISSUE_MANAGEMENT, PROP_TIME_TRACKING);
- DefaultRolesBean defaultRolesBean = new DefaultRolesBean();
- defaultRolesBean.setRoles(getProject().getBaseAuthorizations().stream().map(it->it.getRole()).collect(Collectors.toList()));
-
LabelsBean labelsBean = LabelsBean.of(getProject());
ParentBean parentBean = new ParentBean();
@@ -228,6 +233,29 @@ public class GeneralProjectSettingPage extends ProjectSettingPage {
add(form);
}
+ private Form<?> newDefaultsForm(DefaultRolesBean defaultRolesBean) {
+ var oldAuditContent = VersionedXmlDoc.fromBean(defaultRolesBean).toXML();
+ var form = new Form<Void>("form") {
+
+ @Override
+ protected void onSubmit() {
+ OneDev.getInstance(TransactionService.class).run(() -> {
+ var project = getProject();
+ OneDev.getInstance(BaseAuthorizationService.class).syncRoles(project, defaultRolesBean.getRoles());
+ var newAuditContent = VersionedXmlDoc.fromBean(defaultRolesBean).toXML();
+ auditService.audit(project, "changed general settings", oldAuditContent, newAuditContent);
+ });
+ Session.get().success(_T("General settings updated"));
+ setResponsePage(GeneralProjectSettingPage.class, paramsOf(getProject()));
+ }
+ };
+ form.add(BeanContext.edit("defaultRoleEditor", defaultRolesBean));
+ // Only default roles are inherited; never bind project identity or lifecycle controls here.
+ for (var id : new String[] {"editor", "labelsEditor", "parentEditor", "delete"})
+ form.add(new WebMarkupContainer(id).setVisible(false));
+ return form;
+ }
+
@Override
protected Component newProjectTitle(String componentId) {
return new Label(componentId, _T("General Settings")).add(AttributeAppender.replace("class", "text-truncate"));
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/IssueBranchPrefixPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/IssueBranchPrefixPage.html
index 576113844c..a45336697c 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/IssueBranchPrefixPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/IssueBranchPrefixPage.html
@@ -1,11 +1,4 @@
<wicket:extend>
- <div class="alert alert-notice bg-white shadow mb-5 text-gray">
- <wicket:svg href="bulb" class="icon mr-2"/>
- <wicket:t>
- This setting is inherited from parent project when left empty. The first non-empty value
- found while walking up the project hierarchy will be used.
- </wicket:t>
- </div>
<div class="card">
<div class="card-body">
<form wicket:id="form" class="leave-confirm">
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/ProjectStateTransitionListPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/ProjectStateTransitionListPage.java
index 6738ecf620..a3a453929e 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/ProjectStateTransitionListPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/issuesetting/ProjectStateTransitionListPage.java
@@ -76,6 +76,11 @@ public class ProjectStateTransitionListPage extends ProjectIssueSettingPage {
});
}
+ @Override
+ protected boolean hasProjectDefaults() {
+ return false;
+ }
+
@Override
protected Component newProjectTitle(String componentId) {
return new Label(componentId, _T("Issue State Transitions"));
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/project-setting.css b/server-core/src/main/java/io/onedev/server/web/page/project/setting/project-setting.css
index a77912109e..d5409fbdbf 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/project-setting.css
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/project-setting.css
@@ -1,3 +1,7 @@
+.project-defaults-hint {
+ padding-top: 4px;
+}
+
.project-setting .avatar-edit .current img {
height: 240px;
width: 240px;
@@ -45,4 +49,4 @@
.project-setting .project-authorizations .bean-list td.property-userName {
width: 50%;
-}
\ No newline at end of file
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/setting/servicedesk/ServiceDeskSettingPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/setting/servicedesk/ServiceDeskSettingPage.java
index e8fc7d88ca..057433e89a 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/setting/servicedesk/ServiceDeskSettingPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/setting/servicedesk/ServiceDeskSettingPage.java
@@ -85,6 +85,11 @@ public class ServiceDeskSettingPage extends ProjectSettingPage {
add(form);
}
+ @Override
+ protected boolean hasProjectDefaults() {
+ return false;
+ }
+
@Override
protected Component newProjectTitle(String componentId) {
return new Label(componentId, "<span class='text-truncate'>Service Desk Settings</span>").setEscapeModelStrings(false);
diff --git a/server-core/src/main/java/io/onedev/server/web/page/user/authorization/UserAuthorizationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/user/authorization/UserAuthorizationsPage.java
index 4e9512cac5..8ae250379a 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/user/authorization/UserAuthorizationsPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/user/authorization/UserAuthorizationsPage.java
@@ -19,7 +19,8 @@ import org.apache.wicket.request.mapper.parameter.PageParameters;
import io.onedev.server.OneDev;
import io.onedev.server.data.migration.VersionedXmlDoc;
-import io.onedev.server.service.ProjectService;
+import io.onedev.server.model.Project;
+import io.onedev.server.web.util.WicketUtils;
import io.onedev.server.service.RoleService;
import io.onedev.server.service.UserAuthorizationService;
import io.onedev.server.model.UserAuthorization;
@@ -51,6 +52,8 @@ public class UserAuthorizationsPage extends UserPage {
ProjectAuthorizationsBean authorizationsBean = new ProjectAuthorizationsBean();
var userRoles = new HashMap<String, List<String>>();
for (var authorization: getUser().getProjectAuthorizations()) {
+ if (!WicketUtils.isSubscriptionActive() && Project.DEFAULT_ID.equals(authorization.getProject().getId()))
+ continue;
String projectPath = authorization.getProject().getPath();
String roleName = authorization.getRole().getName();
userRoles.computeIfAbsent(projectPath, k -> new ArrayList<>()).add(roleName);
@@ -75,7 +78,7 @@ public class UserAuthorizationsPage extends UserPage {
error(MessageFormat.format(_T("Duplicate authorizations found: {0}"), authorizationBean.getProjectPath()));
return;
} else {
- var project = getProjectService().findByPath(authorizationBean.getProjectPath());
+ var project = authorizationBean.resolveProject();
authorizationBean.getRoleNames().stream().forEach(it -> {
UserAuthorization authorization = new UserAuthorization();
authorization.setUser(getUser());
@@ -103,8 +106,5 @@ public class UserAuthorizationsPage extends UserPage {
private RoleService getRoleService() {
return OneDev.getInstance(RoleService.class);
}
-
- private ProjectService getProjectService() {
- return OneDev.getInstance(ProjectService.class);
- }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java
index 70333e1df9..cc63bddf92 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_de.java
@@ -980,6 +980,7 @@ public class Translation_de extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "Branch Bean mit Revision erstellen");
m.put("Create Child Project", "Unterprojekt erstellen");
m.put("Create Child Projects", "Unterprojekte erstellen");
+ m.put("Create Dependency Dashboard Issue", "Abhängigkeits-Dashboard-Issue erstellen");
m.put("Create Issue", "Erstelle Problem");
m.put("Create Iteration", "Erstelle Iteration");
m.put("Create Merge Commit", "Erstelle Merge-Commit");
@@ -3044,6 +3045,7 @@ public class Translation_de extends TranslationResourceBundle {
m.put("Paused selected agents", "Ausgewählte Agenten pausiert");
m.put("Pem Private Key", "Pem-Privatschlüssel");
m.put("Pending", "Ausstehend");
+ m.put("Pending review", "Ausstehende Überprüfung");
m.put("Performance", "Leistung");
m.put("Performance Setting", "Leistungseinstellung");
m.put("Performance Settings", "Leistungseinstellungen");
@@ -4201,8 +4203,6 @@ public class Translation_de extends TranslationResourceBundle {
"Geben Sie den zu verwendenden Modellnamen an. <b class='text-danger'>HINWEIS: </b> Derzeit unterstützt OneDev nur\nModelle mit Chat-Vervollständigungs-API. OpenAI-Modelle mit der neuen Antwort-API werden noch nicht unterstützt");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"Geben Sie den privaten Schlüssel (im PEM-Format) an, der vom SSH-Server verwendet wird, um Verbindungen mit dem Client herzustellen");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "Geben Sie den Repository-Ordner an, um Wiki-Seiten zu speichern. Lassen Sie das Feld leer, um vom übergeordneten Element zu erben.\nWenn Sie keine Wiki-Seiten im Projekt-Repository speichern möchten, kann der angegebene Ordner\nein Git-Submodul sein. Um Dateien aus dem Wiki-Seiten-Panel auszuschließen, fügen Sie eine <code>.wikiignore</code>\nDatei im Stammordner des Wikis mit Git-Ignoriermustern relativ zu diesem Ordner hinzu.");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"Geben Sie die Strategie an, um Informationen zur Gruppenmitgliedschaft abzurufen. Um einer LDAP-Gruppe entsprechende Berechtigungen zu erteilen, sollte eine OneDev-Gruppe mit demselben Namen definiert werden. Verwenden Sie die Strategie <tt>Gruppen nicht abrufen</tt>, wenn Sie die Gruppenmitgliedschaften auf der OneDev-Seite verwalten möchten");
m.put("Specify timeout in seconds when communicating with mail server", "Geben Sie das Timeout in Sekunden an, wenn mit dem Mailserver kommuniziert wird");
@@ -4963,6 +4963,8 @@ public class Translation_de extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"Ob das Image beim Ausführen des Containers immer gezogen werden soll. Aktivieren verhindert, dass Images durch bösartige Workloads ersetzt werden, die auf demselben Node laufen.");
m.put("Whether or not to be able to access time tracking info of issues", "Ob auf Zeitverfolgungsinformationen von Problemen zugegriffen werden kann oder nicht");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "Ob ein Abhängigkeits-Dashboard-Issue erstellt werden soll oder nicht. Wenn deaktiviert, wird Renovate keine Issues erstellen oder aktualisieren, und bestehende Issues können manuell geschlossen werden. Optionen wie Rate-Limits können weiterhin über die Renovate-Konfiguration gesteuert werden");
m.put("Whether or not to create the workspace inside container", "Ob der Arbeitsbereich im Container erstellt werden soll oder nicht");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"Ob der Workspace gelöscht werden soll, wenn der Aufgabenbefehl erfolgreich abgeschlossen wird. Deaktivieren Sie dies, wenn\nSie überprüfen möchten, wie der Prompt vom Coding-Agent verarbeitet wird, nachdem der Aufgabenbefehl erfolgreich abgeschlossen wurde.\nBeachten Sie, dass der Workspace nicht automatisch gelöscht wird, wenn der Aufgabenbefehl fehlschlägt.");
@@ -5344,10 +5346,17 @@ public class Translation_de extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "Abhängigkeits-Dashboard-Issue erstellen");
- m.put("Pending review", "Ausstehende Überprüfung");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "Ob ein Abhängigkeits-Dashboard-Issue erstellt werden soll oder nicht. Wenn deaktiviert, wird Renovate keine Issues erstellen oder aktualisieren, und bestehende Issues können manuell geschlossen werden. Optionen wie Rate-Limits können weiterhin über die Renovate-Konfiguration gesteuert werden");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "Alle Stammprojekte können gemeinsame Einstellungen von Administration / Projekteinstellungen übernehmen. Erfordert ein aktives Abonnement.");
+ m.put("Leave empty to inherit from the parent project.", "Leer lassen, um von dem übergeordneten Projekt zu erben.");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "Leer lassen, um die <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>Standardeinstellung</a> zu verwenden.");
+ m.put("Project Defaults", "Projekteinstellungen");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "Wählen Sie <code>~default</code>, um die ausgewählten Rollen auf alle Projekte anzuwenden, einschließlich später erstellter Projekte.");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "Geben Sie den Repository-Ordner an, um Wiki-Seiten zu speichern.\nWenn Sie keine Wiki-Seiten im Projekt-Repository speichern möchten, kann der angegebene Ordner\nein Git-Submodul sein. Um Dateien aus dem Wiki-Seiten-Panel auszuschließen, fügen Sie eine <code>.wikiignore</code>\nDatei im Wiki-Stammordner mit Git-Ignoriermustern relativ zu diesem Ordner hinzu.");
+ m.put("Use default setting", "Standardeinstellung verwenden");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java
index 21c14607ad..a4ee5819d5 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_es.java
@@ -980,6 +980,7 @@ public class Translation_es extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "Bean de Crear Rama con Revisión");
m.put("Create Child Project", "Crear Proyecto Hijo");
m.put("Create Child Projects", "Crear Proyectos Hijos");
+ m.put("Create Dependency Dashboard Issue", "Crear problema del panel de dependencias");
m.put("Create Issue", "Crear problema");
m.put("Create Iteration", "Crear iteración");
m.put("Create Merge Commit", "Crear commit de fusión");
@@ -3044,6 +3045,7 @@ public class Translation_es extends TranslationResourceBundle {
m.put("Paused selected agents", "Se han pausado los agentes seleccionados");
m.put("Pem Private Key", "Clave Privada Pem");
m.put("Pending", "Pendiente");
+ m.put("Pending review", "Revisión pendiente");
m.put("Performance", "Rendimiento");
m.put("Performance Setting", "Configuración de rendimiento");
m.put("Performance Settings", "Configuraciones de rendimiento");
@@ -4201,8 +4203,6 @@ public class Translation_es extends TranslationResourceBundle {
"Especifique el nombre del modelo a usar. <b class='text-danger'>NOTA: </b> Actualmente OneDev solo soporta\nmodelos con API de completaciones de chat. Los modelos de OpenAI con la nueva API de respuestas no están soportados aún");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"Especifique la clave privada (en formato PEM) utilizada por el servidor SSH para establecer conexiones con el cliente");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "Especifique la carpeta del repositorio para almacenar las páginas del wiki. Déjelo vacío para heredar del padre.\nSi no desea almacenar las páginas del wiki en el repositorio del proyecto, la carpeta especificada\npuede ser un submódulo de Git. Para excluir archivos del panel de páginas del wiki, agregue un archivo <code>.wikiignore</code>\nen la carpeta raíz del wiki con patrones de exclusión de Git relativos a esa carpeta");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"Especifique la estrategia para recuperar información de membresía de grupo. Para otorgar permisos apropiados a un grupo LDAP, se debe definir un grupo de OneDev con el mismo nombre. Use la estrategia <tt>No Recuperar Grupos</tt> si desea gestionar las membresías de grupo en el lado de OneDev");
m.put("Specify timeout in seconds when communicating with mail server", "Especifique el tiempo de espera en segundos al comunicarse con el servidor de correo");
@@ -4963,6 +4963,8 @@ public class Translation_es extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"Si se debe o no siempre extraer la imagen al ejecutar el contenedor. Habilitarlo evita que las imágenes sean reemplazadas por cargas de trabajo maliciosas que se ejecutan en el mismo nodo.");
m.put("Whether or not to be able to access time tracking info of issues", "Si se puede acceder o no a la información de seguimiento de tiempo de los problemas");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "Si se debe o no crear un problema del panel de dependencias. Si está deshabilitado, Renovate no creará ni actualizará problemas, y los problemas existentes se pueden cerrar manualmente. Opciones como los límites de velocidad aún se pueden controlar a través de la configuración de Renovate");
m.put("Whether or not to create the workspace inside container", "Si crear o no el espacio de trabajo dentro del contenedor");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"Si eliminar o no el espacio de trabajo si el comando de tarea se completa con éxito. Desmarca esto si\nquieres verificar cómo el agente de codificación procesa el prompt después de que el comando de tarea se complete\ncon éxito. Ten en cuenta que el espacio de trabajo no se eliminará automáticamente si el comando de tarea falla.");
@@ -5344,10 +5346,17 @@ public class Translation_es extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "Crear problema del panel de dependencias");
- m.put("Pending review", "Revisión pendiente");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "Si se debe o no crear un problema del panel de dependencias. Si está deshabilitado, Renovate no creará ni actualizará problemas, y los problemas existentes se pueden cerrar manualmente. Opciones como los límites de velocidad aún se pueden controlar a través de la configuración de Renovate");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "Todos los proyectos raíz pueden heredar configuraciones compartidas desde Administración / Valores Predeterminados del Proyecto. Requiere una suscripción activa.");
+ m.put("Leave empty to inherit from the parent project.", "Dejar vacío para heredar del proyecto padre.");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "Dejar vacío para usar la <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>configuración predeterminada</a>.");
+ m.put("Project Defaults", "Valores Predeterminados del Proyecto");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "Seleccione <code>~default</code> para aplicar los roles seleccionados a todos los proyectos, incluidos los proyectos creados posteriormente");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "Especifique la carpeta del repositorio para almacenar las páginas wiki.\nSi no desea almacenar las páginas wiki en el repositorio del proyecto, la carpeta especificada\npuede ser un submódulo de Git. Para excluir archivos del panel de Páginas Wiki, agregue un archivo <code>.wikiignore</code>\nen la carpeta raíz del wiki con patrones de exclusión de Git relativos a esa carpeta");
+ m.put("Use default setting", "Usar configuración predeterminada");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java
index b726e9025b..ea1e47ea32 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_fr.java
@@ -980,6 +980,7 @@ public class Translation_fr extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "Bean de création de branche avec révision");
m.put("Create Child Project", "Créer un projet enfant");
m.put("Create Child Projects", "Créer des projets enfants");
+ m.put("Create Dependency Dashboard Issue", "Créer un problème de tableau de bord des dépendances");
m.put("Create Issue", "Créer un problème");
m.put("Create Iteration", "Créer une itération");
m.put("Create Merge Commit", "Créer un commit de fusion");
@@ -3044,6 +3045,7 @@ public class Translation_fr extends TranslationResourceBundle {
m.put("Paused selected agents", "Mis en pause les agents sélectionnés");
m.put("Pem Private Key", "Clé privée Pem");
m.put("Pending", "En attente");
+ m.put("Pending review", "En attente de révision");
m.put("Performance", "Performance");
m.put("Performance Setting", "Paramètre de performance");
m.put("Performance Settings", "Paramètres de performance");
@@ -4201,8 +4203,6 @@ public class Translation_fr extends TranslationResourceBundle {
"Spécifiez le nom du modèle à utiliser. <b class='text-danger'>REMARQUE :</b> Actuellement, OneDev ne prend en charge que\nles modèles avec l'API de complétions de chat. Les modèles OpenAI avec la nouvelle API de réponses ne sont pas encore pris en charge");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"Spécifiez la clé privée (au format PEM) utilisée par le serveur SSH pour établir des connexions avec le client");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "Spécifiez le dossier du dépôt pour stocker les pages wiki. Laissez vide pour hériter du parent.\nSi vous ne souhaitez pas stocker les pages wiki dans le dépôt du projet, le dossier spécifié\npeut être un sous-module Git. Pour exclure des fichiers du panneau Pages wiki, ajoutez un fichier <code>.wikiignore</code>\ndans le dossier racine du wiki avec des modèles d'ignorance Git relatifs à ce dossier");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"Spécifiez la stratégie pour récupérer les informations d'appartenance au groupe. Pour attribuer des permissions appropriées à un groupe LDAP, un groupe OneDev portant le même nom doit être défini. Utilisez la stratégie <tt>Ne pas récupérer les groupes</tt> si vous souhaitez gérer les appartenances aux groupes du côté de OneDev");
m.put("Specify timeout in seconds when communicating with mail server", "Spécifiez le délai d'attente en secondes lors de la communication avec le serveur de messagerie");
@@ -4963,6 +4963,8 @@ public class Translation_fr extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"Indique si l'image doit toujours être tirée lors de l'exécution du conteneur. L'activation évite que les images soient remplacées par des charges de travail malveillantes exécutées sur le même nœud.");
m.put("Whether or not to be able to access time tracking info of issues", "Si les informations de suivi du temps des issues peuvent être accessibles ou non");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "Créer ou non un problème de tableau de bord des dépendances. Si désactivé, Renovate ne créera ni ne mettra à jour les problèmes, et les problèmes existants peuvent être fermés manuellement. Des options telles que les limites de taux peuvent toujours être contrôlées via la configuration de Renovate");
m.put("Whether or not to create the workspace inside container", "Créer ou non l'espace de travail à l'intérieur du conteneur");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"Supprimer ou non l'espace de travail si la commande de tâche se termine avec succès. Décochez ceci si\nvous souhaitez vérifier comment le prompt est traité par l'agent de codage après que la commande de tâche se termine\navec succès. Notez que l'espace de travail ne sera pas supprimé automatiquement si la commande de tâche échoue.");
@@ -5344,10 +5346,17 @@ public class Translation_fr extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "Créer un problème de tableau de bord des dépendances");
- m.put("Pending review", "En attente de révision");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "Créer ou non un problème de tableau de bord des dépendances. Si désactivé, Renovate ne créera ni ne mettra à jour les problèmes, et les problèmes existants peuvent être fermés manuellement. Des options telles que les limites de taux peuvent toujours être contrôlées via la configuration de Renovate");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "Tous les projets racines peuvent hériter des paramètres partagés depuis Administration / Paramètres par défaut du projet. Nécessite un abonnement actif.");
+ m.put("Leave empty to inherit from the parent project.", "Laissez vide pour hériter du projet parent.");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "Laissez vide pour utiliser le <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>paramètre par défaut</a>.");
+ m.put("Project Defaults", "Paramètres par défaut du projet");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "Sélectionnez <code>~default</code> pour appliquer les rôles sélectionnés à tous les projets, y compris les projets créés ultérieurement");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "Spécifiez le dossier du dépôt pour stocker les pages wiki.\nSi vous ne souhaitez pas stocker les pages wiki dans le dépôt du projet, le dossier spécifié\npeut être un sous-module Git. Pour exclure des fichiers du panneau des pages wiki, ajoutez un fichier <code>.wikiignore</code>\ndans le dossier racine du wiki avec des modèles d'ignorance Git relatifs à ce dossier");
+ m.put("Use default setting", "Utiliser le paramètre par défaut");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java
index 4a331a1525..2e602b412a 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_it.java
@@ -980,6 +980,7 @@ public class Translation_it extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "Crea Bean del Branch con Revisione");
m.put("Create Child Project", "Crea Progetto Figlio");
m.put("Create Child Projects", "Crea Progetti Figli");
+ m.put("Create Dependency Dashboard Issue", "Crea Problema del Cruscotto delle Dipendenze");
m.put("Create Issue", "Crea Problema");
m.put("Create Iteration", "Crea Iterazione");
m.put("Create Merge Commit", "Crea Commit di Merge");
@@ -3044,6 +3045,7 @@ public class Translation_it extends TranslationResourceBundle {
m.put("Paused selected agents", "Messi in pausa gli agenti selezionati");
m.put("Pem Private Key", "Chiave Privata Pem");
m.put("Pending", "In Attesa");
+ m.put("Pending review", "In attesa di revisione");
m.put("Performance", "Prestazioni");
m.put("Performance Setting", "Impostazione delle prestazioni");
m.put("Performance Settings", "Impostazioni delle prestazioni");
@@ -4201,8 +4203,6 @@ public class Translation_it extends TranslationResourceBundle {
"Specifica il nome del modello da utilizzare. <b class='text-danger'>NOTA: </b> Al momento OneDev supporta solo\nmodelli con l'API di completamento delle chat. I modelli OpenAI con la nuova API di risposte non sono ancora supportati");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"Specifica la chiave privata (in formato PEM) utilizzata dal server SSH per stabilire connessioni con il client");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "Specifica la cartella del repository per memorizzare le pagine wiki. Lascia vuoto per ereditare dal genitore.\nSe non vuoi memorizzare le pagine wiki nel repository del progetto, la cartella specificata\npuò essere un sottogruppo Git. Per escludere file dal pannello delle pagine Wiki, aggiungi un file <code>.wikiignore</code>\nnella cartella radice del wiki con i modelli di esclusione Git relativi a quella cartella");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"Specifica la strategia per recuperare informazioni sull'appartenenza ai gruppi. Per assegnare permessi appropriati a un gruppo LDAP, deve essere definito un gruppo OneDev con lo stesso nome. Usa la strategia <tt>Non Recuperare Gruppi</tt> se desideri gestire le appartenenze ai gruppi sul lato OneDev");
m.put("Specify timeout in seconds when communicating with mail server", "Specifica il timeout in secondi durante la comunicazione con il server di posta");
@@ -4963,6 +4963,8 @@ public class Translation_it extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"Se abilitare o meno il pull sempre dell'immagine quando si esegue il container. L'abilitazione evita che le immagini vengano sostituite da carichi di lavoro dannosi eseguiti sullo stesso nodo.");
m.put("Whether or not to be able to access time tracking info of issues", "Se essere in grado di accedere alle informazioni di tracciamento del tempo dei problemi o meno");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "Se creare o meno un problema del cruscotto delle dipendenze. Se disabilitato, Renovate non creerà né aggiornerà problemi, e i problemi esistenti possono essere chiusi manualmente. Opzioni come i limiti di velocità possono comunque essere controllate tramite la configurazione di Renovate");
m.put("Whether or not to create the workspace inside container", "Se creare o meno l'ambiente di lavoro all'interno del container");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"Se eliminare o meno il workspace se il comando del task viene completato con successo. Deseleziona questa opzione se\nvuoi verificare come il prompt viene elaborato dall'agente di codifica dopo che il comando del task è stato completato\ncon successo. Nota che il workspace non verrà eliminato automaticamente se il comando del task fallisce.");
@@ -5344,10 +5346,17 @@ public class Translation_it extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "Crea Problema del Cruscotto delle Dipendenze");
- m.put("Pending review", "In attesa di revisione");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "Se creare o meno un problema del cruscotto delle dipendenze. Se disabilitato, Renovate non creerà né aggiornerà problemi, e i problemi esistenti possono essere chiusi manualmente. Opzioni come i limiti di velocità possono comunque essere controllate tramite la configurazione di Renovate");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "Tutti i progetti root possono ereditare impostazioni condivise da Amministrazione / Impostazioni Predefinite del Progetto. Richiede un abbonamento attivo.");
+ m.put("Leave empty to inherit from the parent project.", "Lascia vuoto per ereditare dal progetto padre.");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "Lascia vuoto per utilizzare la <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>impostazione predefinita</a>.");
+ m.put("Project Defaults", "Impostazioni Predefinite del Progetto");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "Seleziona <code>~default</code> per applicare i ruoli selezionati a tutti i progetti, inclusi quelli creati successivamente");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "Specifica la cartella del repository per memorizzare le pagine wiki.\nSe non vuoi memorizzare le pagine wiki nel repository del progetto, la cartella specificata\npuò essere un sottomodulo Git. Per escludere file dal pannello delle pagine wiki, aggiungi un file <code>.wikiignore</code>\nnella cartella radice del wiki con i pattern di esclusione di Git relativi a quella cartella");
+ m.put("Use default setting", "Usa l'impostazione predefinita");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java
index a2ec054c62..a093dd8865 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ja.java
@@ -980,6 +980,7 @@ public class Translation_ja extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "リビジョン付きブランチBeanを作成");
m.put("Create Child Project", "子プロジェクトを作成");
m.put("Create Child Projects", "子プロジェクトを作成");
+ m.put("Create Dependency Dashboard Issue", "依存関係ダッシュボードの課題を作成する");
m.put("Create Issue", "課題を作成");
m.put("Create Iteration", "イテレーションを作成");
m.put("Create Merge Commit", "マージコミットを作成");
@@ -3044,6 +3045,7 @@ public class Translation_ja extends TranslationResourceBundle {
m.put("Paused selected agents", "選択されたエージェントを一時停止しました");
m.put("Pem Private Key", "Pem秘密鍵");
m.put("Pending", "保留中");
+ m.put("Pending review", "レビュー待ち");
m.put("Performance", "パフォーマンス");
m.put("Performance Setting", "パフォーマンス設定");
m.put("Performance Settings", "パフォーマンス設定");
@@ -4201,8 +4203,6 @@ public class Translation_ja extends TranslationResourceBundle {
"使用するモデル名を指定します。<b class='text-danger'>注意:</b> 現在、OneDevは\nチャット完了APIを持つモデルのみをサポートしています。OpenAIの新しい応答APIを持つモデルはまだサポートされていません");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"SSHサーバーがクライアントとの接続を確立するために使用する秘密鍵(PEM形式)を指定してください。");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "Wikiページを保存するリポジトリフォルダーを指定してください。親から継承する場合は空のままにします。\nプロジェクトリポジトリにWikiページを保存したくない場合、指定されたフォルダー\nはGitサブモジュールにすることができます。Wikiページパネルからファイルを除外するには、<code>.wikiignore</code>\nファイルをWikiルートフォルダーに作成し、そのフォルダーに対するGit無視パターンを追加してください");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"グループメンバーシップ情報を取得する戦略を指定してください。LDAPグループに適切な権限を付与するには、同じ名前のOneDevグループを定義する必要があります。グループメンバーシップをOneDev側で管理したい場合は、<tt>グループを取得しない</tt>戦略を使用してください。");
m.put("Specify timeout in seconds when communicating with mail server", "メールサーバーと通信する際のタイムアウトを秒単位で指定してください。");
@@ -4963,6 +4963,8 @@ public class Translation_ja extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"コンテナを実行する際に常にイメージをプルするかどうかを指定します。有効にすると、同じノード上で実行される悪意のあるワークロードによってイメージが置き換えられるのを防ぎます。");
m.put("Whether or not to be able to access time tracking info of issues", "課題のタイムトラッキング情報にアクセスできるかどうか");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "依存関係ダッシュボードの課題を作成するかどうか。無効にすると、Renovate は課題を作成または更新せず、既存の課題は手動で閉じることができます。レート制限などのオプションは、Renovate の設定を通じて引き続き制御できます");
m.put("Whether or not to create the workspace inside container", "コンテナ内にワークスペースを作成するかどうか");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"タスクコマンドが正常に完了した場合にワークスペースを削除するかどうか。\nタスクコマンドが正常に完了した後、コーディングエージェントがプロンプトをどのように処理するかを確認したい場合は、このチェックを外してください。\nタスクコマンドが失敗した場合、ワークスペースは自動的に削除されないことに注意してください。");
@@ -5344,10 +5346,17 @@ public class Translation_ja extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "依存関係ダッシュボードの課題を作成する");
- m.put("Pending review", "レビュー待ち");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "依存関係ダッシュボードの課題を作成するかどうか。無効にすると、Renovate は課題を作成または更新せず、既存の課題は手動で閉じることができます。レート制限などのオプションは、Renovate の設定を通じて引き続き制御できます");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "すべてのルートプロジェクトは、管理 / プロジェクトデフォルトから共有設定を継承できます。有効なサブスクリプションが必要です。");
+ m.put("Leave empty to inherit from the parent project.", "親プロジェクトから継承する場合は空のままにしてください。");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "<a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>デフォルト設定</a>を使用する場合は空のままにしてください。");
+ m.put("Project Defaults", "プロジェクトデフォルト");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "選択したロールをすべてのプロジェクト(後で作成されるプロジェクトを含む)に適用するには、<code>~default</code>を選択してください。");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "Wikiページを保存するリポジトリフォルダーを指定してください。\nプロジェクトリポジトリにWikiページを保存したくない場合、指定されたフォルダー\nはGitサブモジュールにすることができます。Wikiページパネルからファイルを除外するには、<code>.wikiignore</code>\nファイルをWikiルートフォルダーに追加し、そのフォルダーに対するGit無視パターンを記述してください。");
+ m.put("Use default setting", "デフォルト設定を使用");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java
index a7d030a600..5b3bfd53b3 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_ko.java
@@ -980,6 +980,7 @@ public class Translation_ko extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "수정본과 함께 브랜치 빈 생성");
m.put("Create Child Project", "하위 프로젝트 생성");
m.put("Create Child Projects", "하위 프로젝트들 생성");
+ m.put("Create Dependency Dashboard Issue", "종속성 대시보드 이슈 생성");
m.put("Create Issue", "이슈 생성");
m.put("Create Iteration", "반복 생성");
m.put("Create Merge Commit", "병합 커밋 생성");
@@ -3044,6 +3045,7 @@ public class Translation_ko extends TranslationResourceBundle {
m.put("Paused selected agents", "선택된 에이전트가 일시 중지되었습니다.");
m.put("Pem Private Key", "Pem 개인 키");
m.put("Pending", "대기 중");
+ m.put("Pending review", "검토 대기 중");
m.put("Performance", "성능");
m.put("Performance Setting", "성능 설정");
m.put("Performance Settings", "성능 설정들");
@@ -4201,8 +4203,6 @@ public class Translation_ko extends TranslationResourceBundle {
"사용할 모델 이름을 지정하십시오. <b class='text-danger'>참고:</b> 현재 OneDev는\n채팅 완료 API가 있는 모델만 지원합니다. OpenAI의 새로운 응답 API가 있는 모델은 아직 지원되지 않습니다");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"SSH 서버가 클라이언트와 연결을 설정하는 데 사용하는 개인 키(PEM 형식)를 지정하십시오.");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "위키 페이지를 저장할 저장소 폴더를 지정하세요. 상위에서 상속받으려면 비워 두세요.\n프로젝트 저장소에 위키 페이지를 저장하지 않으려면, 지정된 폴더는\nGit 서브모듈일 수 있습니다. 위키 페이지 패널에서 파일을 제외하려면, 위키 루트 폴더에 Git 무시 패턴을 포함한 <code>.wikiignore</code>\n파일을 추가하세요.");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"그룹 멤버십 정보를 검색하는 전략을 지정하십시오. LDAP 그룹에 적절한 권한을 부여하려면 동일한 이름의 OneDev 그룹을 정의해야 합니다. 그룹 멤버십을 OneDev 측에서 관리하려면 <tt>그룹 검색 안 함</tt> 전략을 사용하십시오.");
m.put("Specify timeout in seconds when communicating with mail server", "메일 서버와 통신할 때의 타임아웃(초)을 지정하십시오.");
@@ -4963,6 +4963,8 @@ public class Translation_ko extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"컨테이너를 실행할 때 항상 이미지를 가져올지 여부. 활성화하면 동일한 노드에서 실행 중인 악성 워크로드에 의해 이미지가 대체되는 것을 방지합니다.");
m.put("Whether or not to be able to access time tracking info of issues", "문제의 시간 추적 정보를 액세스할 수 있는지 여부");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "종속성 대시보드 이슈를 생성할지 여부입니다. 비활성화된 경우, Renovate는 이슈를 생성하거나 업데이트하지 않으며, 기존 이슈는 수동으로 닫을 수 있습니다. 속도 제한과 같은 옵션은 여전히 Renovate 구성으로 제어할 수 있습니다.");
m.put("Whether or not to create the workspace inside container", "컨테이너 내부에 워크스페이스를 생성할지 여부");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"작업 명령이 성공적으로 완료되면 워크스페이스를 삭제할지 여부.\n작업 명령이 성공적으로 완료된 후 코딩 에이전트가 프롬프트를 처리하는 방식을 확인하려면 이 옵션을 선택 해제하세요.\n작업 명령이 실패한 경우 워크스페이스는 자동으로 삭제되지 않습니다.");
@@ -5344,10 +5346,17 @@ public class Translation_ko extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "종속성 대시보드 이슈 생성");
- m.put("Pending review", "검토 대기 중");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "종속성 대시보드 이슈를 생성할지 여부입니다. 비활성화된 경우, Renovate는 이슈를 생성하거나 업데이트하지 않으며, 기존 이슈는 수동으로 닫을 수 있습니다. 속도 제한과 같은 옵션은 여전히 Renovate 구성으로 제어할 수 있습니다.");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "모든 루트 프로젝트는 Administration / Project Defaults에서 공유 설정을 상속받을 수 있습니다. 활성 구독이 필요합니다.");
+ m.put("Leave empty to inherit from the parent project.", "상위 프로젝트에서 상속받으려면 비워 두세요.");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "<a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>기본 설정</a>을 사용하려면 비워 두세요.");
+ m.put("Project Defaults", "프로젝트 기본값");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "선택한 역할을 모든 프로젝트(이후에 생성된 프로젝트 포함)에 적용하려면 <code>~default</code>를 선택하세요.");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "위키 페이지를 저장할 저장소 폴더를 지정하세요.\n프로젝트 저장소에 위키 페이지를 저장하지 않으려면, 지정된 폴더는\nGit 서브모듈일 수 있습니다. 위키 페이지 패널에서 파일을 제외하려면, 위키 루트 폴더에\n해당 폴더를 기준으로 Git 무시 패턴을 포함한 <code>.wikiignore</code> 파일을 추가하세요.");
+ m.put("Use default setting", "기본 설정 사용");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java
index d30eab37d3..c7cce6979e 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_pt.java
@@ -980,6 +980,7 @@ public class Translation_pt extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "Bean de Criação de Branch com Revisão");
m.put("Create Child Project", "Criar Projeto Filho");
m.put("Create Child Projects", "Criar Projetos Filhos");
+ m.put("Create Dependency Dashboard Issue", "Criar Problema no Painel de Dependências");
m.put("Create Issue", "Criar Problema");
m.put("Create Iteration", "Criar Iteração");
m.put("Create Merge Commit", "Criar Commit de Mesclagem");
@@ -3044,6 +3045,7 @@ public class Translation_pt extends TranslationResourceBundle {
m.put("Paused selected agents", "Agentes selecionados foram pausados");
m.put("Pem Private Key", "Chave Privada Pem");
m.put("Pending", "Pendente");
+ m.put("Pending review", "Aguardando revisão");
m.put("Performance", "Desempenho");
m.put("Performance Setting", "Configuração de Desempenho");
m.put("Performance Settings", "Configurações de Desempenho");
@@ -4201,8 +4203,6 @@ public class Translation_pt extends TranslationResourceBundle {
"Especifique o nome do modelo a ser usado. <b class='text-danger'>NOTA: </b> No momento, o OneDev só suporta\nmodelos com API de conclusões de chat. Modelos OpenAI com a nova API de respostas ainda não são suportados");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"Especifique a chave privada (em formato PEM) usada pelo servidor SSH para estabelecer conexões com o cliente");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "Especifique a pasta do repositório para armazenar as páginas do wiki. Deixe vazio para herdar do pai.\nSe você não quiser armazenar as páginas do wiki no repositório do projeto, a pasta especificada\npode ser um submódulo Git. Para excluir arquivos do painel de Páginas do wiki, adicione um arquivo <code>.wikiignore</code>\nna pasta raiz do wiki com padrões de exclusão do Git relativos a essa pasta");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"Especifique a estratégia para recuperar informações de associação de grupo. Para conceder permissões apropriadas a um grupo LDAP, um grupo OneDev com o mesmo nome deve ser definido. Use a estratégia <tt>Não Recuperar Grupos</tt> se desejar gerenciar associações de grupo no lado do OneDev");
m.put("Specify timeout in seconds when communicating with mail server", "Especifique o tempo limite em segundos ao se comunicar com o servidor de e-mail");
@@ -4963,6 +4963,8 @@ public class Translation_pt extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"Se deve ou não sempre puxar a imagem ao executar o contêiner. Habilitar evita que imagens sejam substituídas por cargas de trabalho maliciosas executadas no mesmo nó.");
m.put("Whether or not to be able to access time tracking info of issues", "Se será possível acessar informações de rastreamento de tempo das issues ou não");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "Se deve ou não criar um problema no painel de dependências. Se desativado, o Renovate não criará ou atualizará problemas, e problemas existentes podem ser fechados manualmente. Opções como limites de taxa ainda podem ser controladas por meio da configuração do Renovate");
m.put("Whether or not to create the workspace inside container", "Se deve ou não criar o espaço de trabalho dentro do contêiner");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"Se deve ou não excluir o workspace se o comando da tarefa for concluído com sucesso. Desmarque isso se\nvocê quiser verificar como o prompt é processado pelo agente de codificação após o comando da tarefa ser concluído\ncom sucesso. Observe que o workspace não será excluído automaticamente se o comando da tarefa falhar.");
@@ -5344,10 +5346,17 @@ public class Translation_pt extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "Criar Problema no Painel de Dependências");
- m.put("Pending review", "Aguardando revisão");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "Se deve ou não criar um problema no painel de dependências. Se desativado, o Renovate não criará ou atualizará problemas, e problemas existentes podem ser fechados manualmente. Opções como limites de taxa ainda podem ser controladas por meio da configuração do Renovate");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "Todos os projetos raiz podem herdar configurações compartilhadas de Administração / Padrões de Projeto. Requer uma assinatura ativa.");
+ m.put("Leave empty to inherit from the parent project.", "Deixe vazio para herdar do projeto pai.");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "Deixe vazio para usar a <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>configuração padrão</a>.");
+ m.put("Project Defaults", "Padrões de Projeto");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "Selecione <code>~default</code> para aplicar os papéis selecionados a todos os projetos, incluindo projetos criados posteriormente");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "Especifique a pasta do repositório para armazenar páginas wiki.\nSe você não quiser armazenar páginas wiki no repositório do projeto, a pasta especificada\npode ser um submódulo Git. Para excluir arquivos do painel de Páginas Wiki, adicione um arquivo <code>.wikiignore</code>\nna pasta raiz do wiki com padrões de exclusão do Git relativos a essa pasta");
+ m.put("Use default setting", "Usar configuração padrão");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java b/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java
index 4c4b314553..369a56b16f 100644
--- a/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java
+++ b/server-core/src/main/java/io/onedev/server/web/translation/Translation_zh.java
@@ -1006,6 +1006,7 @@ public class Translation_zh extends TranslationResourceBundle {
m.put("Create Branch Bean With Revision", "带版本的创建分支 Bean");
m.put("Create Child Project", "创建子项目");
m.put("Create Child Projects", "创建子项目");
+ m.put("Create Dependency Dashboard Issue", "创建依赖仪表板工单");
m.put("Create Issue", "创建工单");
m.put("Create Iteration", "创建迭代");
m.put("Create Merge Commit", "创建合并提交");
@@ -3070,6 +3071,7 @@ public class Translation_zh extends TranslationResourceBundle {
m.put("Paused selected agents", "已暂停选定的代理");
m.put("Pem Private Key", "PEM 私钥");
m.put("Pending", "待处理");
+ m.put("Pending review", "待处理审核");
m.put("Performance", "性能");
m.put("Performance Setting", "性能设置");
m.put("Performance Settings", "性能设置");
@@ -4227,8 +4229,6 @@ public class Translation_zh extends TranslationResourceBundle {
"指定要使用的模型名称。<b class='text-danger'>注意:</b>目前 OneDev 仅支持\n具有聊天完成 API 的模型。尚不支持具有新响应 API 的 OpenAI 模型。");
m.put("Specify the private key (in PEM format) used by SSH server to establish connections with client",
"指定用于与客户端建立连接的 SSH 服务器使用的私钥(在 PEM 格式中)");
- m.put("Specify the repository folder to store wiki pages. Leave empty to inherit from parent.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
- "指定存储 wiki 页面的仓库文件夹。留空以继承自父级。\n如果您不想将 wiki 页面存储在项目仓库中,指定的文件夹\n可以是一个 Git 子模块。要从 wiki 页面面板中排除文件,请在 wiki 根文件夹中添加一个 <code>.wikiignore</code>\n文件,并使用相对于该文件夹的 Git 忽略模式");
m.put("Specify the strategy to retrieve group membership information. To give appropriate permissions to a LDAP group, a OneDev group with same name should be defined. Use strategy <tt>Do Not Retrieve Groups</tt> if you want to manage group memberships at OneDev side",
"指定查询组成员信息的策略。要为 LDAP 组分配适当权限,应定义一个同名的 OneDev 组。如果您希望在 OneDev 端管理组成员关系,请使用策略 <tt>不查询组</tt>");
m.put("Specify timeout in seconds when communicating with mail server", "指定与邮件服务器通信时的超时时间(秒)");
@@ -4989,6 +4989,8 @@ public class Translation_zh extends TranslationResourceBundle {
m.put("Whether or not to always pull the image when running the container. Enabling avoids images being replaced by malicious workloads running on the same node.",
"运行容器时是否总是拉取镜像。启用此选项可以避免镜像被运行在同一节点上的恶意工作负载替换。");
m.put("Whether or not to be able to access time tracking info of issues", "是否能够访问工单的时间跟踪信息");
+ m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
+ "是否创建依赖仪表板工单。如果禁用,Renovate 将不会创建或更新工单,现有工单可以手动关闭。选项如速率限制仍然可以通过 Renovate 配置进行控制");
m.put("Whether or not to create the workspace inside container", "是否在容器内创建工作区");
m.put("Whether or not to delete workspace if task command completes successfully. Uncheck this if\nyou want to check how the prompt is processed by coding agent after task command completes\nsuccessfully. Note that workspace will not be deleted automatically if task command fails.",
"是否在任务命令成功完成后删除工作区。如果您想检查任务命令成功完成后编码代理如何处理提示,请取消选中此选项。\n请注意,如果任务命令失败,工作区将不会自动删除。");
@@ -5370,10 +5372,17 @@ public class Translation_zh extends TranslationResourceBundle {
m.put("{jakarta.validation.constraints.NotEmpty.message}", "{jakarta.validation.constraints.NotEmpty.message}");
m.put("{jakarta.validation.constraints.NotNull.message}", "{jakarta.validation.constraints.NotNull.message}");
m.put("{jakarta.validation.constraints.Size.message}", "{jakarta.validation.constraints.Size.message}");
- m.put("Create Dependency Dashboard Issue", "创建依赖仪表板工单");
- m.put("Pending review", "待处理审核");
- m.put("Whether or not to create a dependency dashboard issue. If disabled, Renovate will not create or update issues, and existing issues can be closed manually. Options such as rate limits can still be controlled via Renovate configuration",
- "是否创建依赖仪表板工单。如果禁用,Renovate 将不会创建或更新工单,现有工单可以手动关闭。选项如速率限制仍然可以通过 Renovate 配置进行控制");
+ m.put("All root projects can inherit shared settings from Administration / Project Defaults. Requires an active subscription.",
+ "所有根项目可以从 Administration / Project Defaults 继承共享设置。需要一个有效订阅。");
+ m.put("Leave empty to inherit from the parent project.", "留空以继承父项目的设置。");
+ m.put("Leave empty to use the <a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>.",
+ "留空以使用<a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>默认设置</a>。");
+ m.put("Project Defaults", "项目默认值");
+ m.put("Select <code>~default</code> to apply the selected roles to all projects, including projects created later",
+ "选择 <code>~default</code> 以将选定的角色应用于所有项目,包括后续创建的项目");
+ m.put("Specify the repository folder to store wiki pages.\nIf you do not want to store wiki pages in the project repository, the specified folder\ncan be a Git submodule. To exclude files from the wiki Pages panel, add a <code>.wikiignore</code>\nfile in the wiki root folder with Git ignore patterns relative to that folder",
+ "指定存储 wiki 页面的存储库文件夹。\n如果您不想将 wiki 页面存储在项目存储库中,指定的文件夹\n可以是一个 Git 子模块。要从 wiki 页面面板中排除文件,请在 wiki 根文件夹中添加一个 <code>.wikiignore</code>\n文件,并使用相对于该文件夹的 Git 忽略模式");
+ m.put("Use default setting", "使用默认设置");
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBean.java b/server-core/src/main/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBean.java
index e3f426b172..47bf067c56 100644
--- a/server-core/src/main/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBean.java
@@ -1,6 +1,9 @@
package io.onedev.server.web.util.editbean;
+import static io.onedev.server.web.translation.Translation._T;
+
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.List;
import jakarta.validation.constraints.NotEmpty;
@@ -9,6 +12,12 @@ import jakarta.validation.constraints.Size;
import io.onedev.server.annotation.Editable;
import io.onedev.server.annotation.ProjectChoice;
import io.onedev.server.annotation.RoleChoice;
+import io.onedev.server.OneDev;
+import io.onedev.server.exception.NoSubscriptionException;
+import io.onedev.server.model.Project;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.web.util.WicketUtils;
@Editable
public class ProjectAuthorizationBean implements Serializable {
@@ -19,8 +28,8 @@ public class ProjectAuthorizationBean implements Serializable {
private List<String> roleNames;
- @Editable(order=100, name="Project")
- @ProjectChoice
+ @Editable(order=100, name="Project", descriptionProvider="getProjectDescription")
+ @ProjectChoice("getProjectChoices")
@NotEmpty
public String getProjectPath() {
return projectPath;
@@ -30,6 +39,35 @@ public class ProjectAuthorizationBean implements Serializable {
this.projectPath = projectPath;
}
+ @SuppressWarnings("unused")
+ private static String getProjectDescription() {
+ if (SecurityUtils.isAdministrator() && WicketUtils.isSubscriptionActive())
+ return _T("Select <code>~default</code> to apply the selected roles to all projects, including projects created later");
+ else
+ return "";
+ }
+
+ @SuppressWarnings("unused")
+ private static List<Project> getProjectChoices() {
+ var projectService = OneDev.getInstance(ProjectService.class);
+ var cache = projectService.cloneCache();
+ var projects = new ArrayList<>(cache.getProjects());
+ projects.sort(cache.comparingPath());
+ if (WicketUtils.isSubscriptionActive())
+ projects.add(0, projectService.load(Project.DEFAULT_ID));
+ return projects;
+ }
+
+ public Project resolveProject() {
+ var projectService = OneDev.getInstance(ProjectService.class);
+ if (Project.DEFAULT_NAME.equals(projectPath)) {
+ if (!WicketUtils.isSubscriptionActive())
+ throw new NoSubscriptionException("Project defaults");
+ return projectService.load(Project.DEFAULT_ID);
+ }
+ return projectService.findByPath(projectPath);
+ }
+
@Editable(order=200, name="Role")
@RoleChoice
@Size(min=1, message="At least one role is required")
diff --git a/server-core/src/main/java/org/hibernate/validator/internal/engine/ValidatorImpl.java b/server-core/src/main/java/org/hibernate/validator/internal/engine/ValidatorImpl.java
index 22ac459a20..7a5e298869 100644
--- a/server-core/src/main/java/org/hibernate/validator/internal/engine/ValidatorImpl.java
+++ b/server-core/src/main/java/org/hibernate/validator/internal/engine/ValidatorImpl.java
@@ -1371,13 +1371,16 @@ public class ValidatorImpl implements Validator, ExecutableValidator {
* constraints, including annotations of the same type with different attributes.
*/
private boolean isConstraintFromOverriddenMethod(ConstraintLocation location, Class<?> beanClass, Class<? extends Annotation> constraintAnnotationType) {
+ boolean containerElement = location instanceof TypeArgumentConstraintLocation;
+ if (containerElement)
+ location = ((TypeArgumentConstraintLocation) location).getOuterDelegate();
if (location instanceof GetterConstraintLocation) {
GetterConstraintLocation getterLocation = (GetterConstraintLocation) location;
String propertyName = getterLocation.getPropertyName();
Method getter = BeanUtils.findGetter(beanClass, propertyName);
if (getter != null) {
return getter.getDeclaringClass() != getterLocation.getDeclaringClass()
- || getter.getAnnotation(constraintAnnotationType) == null;
+ || !containerElement && getter.getAnnotation(constraintAnnotationType) == null;
}
}
@@ -1398,7 +1401,7 @@ public class ValidatorImpl implements Validator, ExecutableValidator {
}
if (location instanceof AbstractPropertyConstraintLocation && valueContext.getCurrentBean() != null) {
// Check if this constraint comes from a superclass method that has been overridden
- if (isConstraintFromOverriddenMethod(location, valueContext.getCurrentBean().getClass(), metaConstraint.getDescriptor().getAnnotationType())) {
+ if (isConstraintFromOverriddenMethod(metaConstraint.getLocation(), valueContext.getCurrentBean().getClass(), metaConstraint.getDescriptor().getAnnotationType())) {
return false; // Skip validation for constraints from overridden superclass methods
}
var bean = valueContext.getCurrentBean();
@@ -1777,7 +1780,11 @@ public class ValidatorImpl implements Validator, ExecutableValidator {
}
private boolean isPropertyConstraint(MetaConstraint<?> metaConstraint) {
- ConstraintLocationKind kind = metaConstraint.getLocation().getKind();
+ var location = metaConstraint.getLocation();
+ // Container elements must be validated in the same phase as their owning property.
+ if (location instanceof TypeArgumentConstraintLocation)
+ location = ((TypeArgumentConstraintLocation) location).getOuterDelegate();
+ ConstraintLocationKind kind = location.getKind();
return kind == ConstraintLocationKind.FIELD || kind == ConstraintLocationKind.GETTER;
}
diff --git a/server-core/src/test/java/io/onedev/server/logging/build/BuildLogPersistenceTest.java b/server-core/src/test/java/io/onedev/server/logging/build/BuildLogPersistenceTest.java
index b65cea80fb..31de900a57 100644
--- a/server-core/src/test/java/io/onedev/server/logging/build/BuildLogPersistenceTest.java
+++ b/server-core/src/test/java/io/onedev/server/logging/build/BuildLogPersistenceTest.java
@@ -23,6 +23,7 @@ import io.onedev.commons.utils.TaskLogger;
import io.onedev.k8shelper.JobHelper;
import io.onedev.k8shelper.JobHelper.StepEventKind;
import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
import io.onedev.server.cluster.ClusterService;
import io.onedev.server.event.ListenerRegistry;
import io.onedev.server.job.JobService;
@@ -113,6 +114,7 @@ class BuildLogPersistenceTest {
services.when(() -> OneDev.getInstance(BuildService.class)).thenReturn(builds);
services.when(() -> OneDev.getInstance(JobService.class)).thenReturn(mock(JobService.class));
services.when(() -> OneDev.getInstance(ListenerRegistry.class)).thenReturn(mock(ListenerRegistry.class));
+ services.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(mock(SubscriptionService.class));
var logs = mock(BuildLogService.class);
when(logs.newLogger(any(), any())).thenReturn(mock(TaskLogger.class));
var router = new BuildLogRouter(build, logs);
diff --git a/server-core/src/test/java/io/onedev/server/model/ProjectSettingsInheritanceTest.java b/server-core/src/test/java/io/onedev/server/model/ProjectSettingsInheritanceTest.java
new file mode 100644
index 0000000000..88796463de
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/model/ProjectSettingsInheritanceTest.java
@@ -0,0 +1,210 @@
+package io.onedev.server.model;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.model.support.build.BuildPreservation;
+import io.onedev.server.model.support.build.DefaultFixedIssueFilter;
+import io.onedev.server.model.support.build.JobProperty;
+import io.onedev.server.model.support.build.JobSecret;
+import io.onedev.server.model.support.build.ProjectBuildSetting;
+import io.onedev.server.model.support.code.BranchProtection;
+import io.onedev.server.model.support.code.TagProtection;
+import io.onedev.server.model.support.pullrequest.MergeStrategy;
+import io.onedev.server.model.support.WebHook;
+import io.onedev.server.model.support.wiki.SpecifiedPath;
+import io.onedev.server.model.support.workspace.spec.WorkspaceSpec;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.service.UserService;
+
+public class ProjectSettingsInheritanceTest {
+
+ private MockedStatic<OneDev> oneDev;
+ private SubscriptionService subscription;
+ private ProjectService projects;
+ private Project defaults;
+ private Project root;
+ private Project child;
+
+ @BeforeEach
+ void setUp() {
+ oneDev = mockStatic(OneDev.class);
+ subscription = mock(SubscriptionService.class);
+ projects = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(subscription);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ root = project(1L, "root");
+ child = project(2L, "child");
+ child.setParent(root);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ when(subscription.isSubscriptionActive()).thenReturn(true);
+ }
+
+ @AfterEach
+ void tearDown() {
+ oneDev.close();
+ }
+
+ private Project project(Long id, String name) {
+ var project = new Project();
+ project.setId(id);
+ project.setName(name);
+ return project;
+ }
+
+ @Test
+ void defaultsExtendSettingsButNotTheProjectTree() {
+ assertSame(defaults, root.getSettingsParent());
+ assertSame(root, child.getSettingsParent());
+ assertNull(defaults.getSettingsParent());
+ assertNull(root.getParent());
+ assertEquals("root/child", child.calcPath());
+ assertFalse(defaults.isSelfOrAncestorOf(child));
+ assertTrue(defaults.isSelfOrSettingsAncestorOf(child));
+ assertTrue(root.isSelfOrSettingsAncestorOf(child));
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertNull(root.getSettingsParent());
+ assertSame(root, child.getSettingsParent());
+ assertFalse(defaults.isSelfOrSettingsAncestorOf(child));
+ }
+
+ @Test
+ void scalarSettingsUseDefaultsAndAllowRootAndChildOverrides() {
+ defaults.getCodeIndexingSetting().setAnalyzeFiles("**.java");
+ defaults.getCodeIndexingSetting().setRequireLoginForAutoIndexing(true);
+ defaults.getAiSetting().setExcludedReviewFiles("vendor/**");
+ defaults.getIssueSetting().setBranchPrefix("issue-");
+ defaults.getBuildSetting().setCachePreserveDays(30);
+ defaults.getPullRequestSetting().setDefaultMergeStrategy(MergeStrategy.SQUASH_SOURCE_BRANCH_COMMITS);
+ defaults.getPullRequestSetting().setDeleteSourceBranchAfterMerge(true);
+ var folder = new SpecifiedPath();
+ folder.setPath("docs");
+ defaults.getWikiSetting().setFolder(folder);
+ for (var project : List.of(root, child)) {
+ assertEquals("**.java", project.findCodeAnalysisFiles());
+ assertTrue(project.findRequireLoginForAutoIndexing());
+ assertEquals("vendor/**", project.findExcludedAiReviewFiles());
+ assertEquals("issue-", project.findIssueBranchPrefix());
+ assertEquals(30, project.getHierarchyCachePreserveDays());
+ assertEquals(MergeStrategy.SQUASH_SOURCE_BRANCH_COMMITS, project.findDefaultPullRequestMergeStrategy());
+ assertTrue(project.findDeleteBranchAfterPullRequestMerge());
+ assertSame(folder, project.getWikiFolder());
+ }
+ root.getCodeIndexingSetting().setAnalyzeFiles("**.go");
+ root.getCodeIndexingSetting().setRequireLoginForAutoIndexing(false);
+ root.getAiSetting().setExcludedReviewFiles("generated/**");
+ root.getIssueSetting().setBranchPrefix("ticket-");
+ root.getBuildSetting().setCachePreserveDays(10);
+ root.getPullRequestSetting().setDefaultMergeStrategy(MergeStrategy.CREATE_MERGE_COMMIT);
+ root.getPullRequestSetting().setDeleteSourceBranchAfterMerge(false);
+ var rootFolder = new SpecifiedPath();
+ root.getWikiSetting().setFolder(rootFolder);
+ assertEquals("**.go", child.findCodeAnalysisFiles());
+ assertFalse(child.findRequireLoginForAutoIndexing());
+ assertEquals("generated/**", child.findExcludedAiReviewFiles());
+ assertEquals("ticket-", child.findIssueBranchPrefix());
+ assertEquals(10, child.getHierarchyCachePreserveDays());
+ assertEquals(MergeStrategy.CREATE_MERGE_COMMIT, child.findDefaultPullRequestMergeStrategy());
+ assertFalse(child.findDeleteBranchAfterPullRequestMerge());
+ assertSame(rootFolder, child.getWikiFolder());
+ child.getIssueSetting().setBranchPrefix("child-");
+ assertEquals("child-", child.findIssueBranchPrefix());
+ }
+
+ @Test
+ void inactiveSubscriptionKeepsBuiltInFallbacks() {
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertEquals("**", child.findCodeAnalysisFiles());
+ assertFalse(child.findRequireLoginForAutoIndexing());
+ assertNull(child.findExcludedAiReviewFiles());
+ assertNull(child.findIssueBranchPrefix());
+ assertEquals(ProjectBuildSetting.DEFAULT_CACHE_PRESERVE_DAYS, child.getHierarchyCachePreserveDays());
+ assertEquals(MergeStrategy.CREATE_MERGE_COMMIT, child.findDefaultPullRequestMergeStrategy());
+ assertFalse(child.findDeleteBranchAfterPullRequestMerge());
+ assertEquals("wiki", child.getWikiFolder().getPath());
+ assertTrue(child.findDefaultPullRequestAssignees().isEmpty());
+ verify(projects, never()).load(Project.DEFAULT_ID);
+ }
+
+ @Test
+ void additiveSettingsKeepChildParentDefaultOrderAndIgnoreInactiveDefaults() {
+ var defaultBranch = new BranchProtection();
+ var rootBranch = new BranchProtection();
+ var childBranch = new BranchProtection();
+ defaults.getBranchProtections().add(defaultBranch);
+ root.getBranchProtections().add(rootBranch);
+ child.getBranchProtections().add(childBranch);
+ var tag = new TagProtection();
+ var secret = new JobSecret();
+ var filter = new DefaultFixedIssueFilter();
+ var preservation = new BuildPreservation();
+ var hook = new WebHook();
+ defaults.getTagProtections().add(tag);
+ defaults.getBuildSetting().getJobSecrets().add(secret);
+ defaults.getBuildSetting().getDefaultFixedIssueFilters().add(filter);
+ defaults.getBuildSetting().getBuildPreservations().add(preservation);
+ defaults.getWebHooks().add(hook);
+ assertEquals(List.of(childBranch, rootBranch, defaultBranch), child.getHierarchyBranchProtections());
+ assertEquals(List.of(tag), child.getHierarchyTagProtections());
+ assertEquals(List.of(secret), child.getHierarchyJobSecrets());
+ assertEquals(List.of(filter), child.getHierarchyDefaultFixedIssueFilters());
+ assertEquals(List.of(preservation), child.getHierarchyBuildPreservations());
+ assertEquals(List.of(hook), child.getHierarchyWebHooks());
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertEquals(List.of(childBranch, rootBranch), child.getHierarchyBranchProtections());
+ assertTrue(child.getHierarchyTagProtections().isEmpty());
+ assertTrue(child.getHierarchyJobSecrets().isEmpty());
+ assertTrue(child.getHierarchyDefaultFixedIssueFilters().isEmpty());
+ assertTrue(child.getHierarchyBuildPreservations().isEmpty());
+ assertTrue(child.getHierarchyWebHooks().isEmpty());
+ }
+
+ @Test
+ void namedSettingsOverrideDefaultsByName() {
+ var defaultProperty = new JobProperty();
+ defaultProperty.setName("image");
+ var rootProperty = new JobProperty();
+ rootProperty.setName("image");
+ defaults.getBuildSetting().getJobProperties().add(defaultProperty);
+ assertEquals(List.of(defaultProperty), root.getHierarchyJobProperties());
+ root.getBuildSetting().getJobProperties().add(rootProperty);
+ assertEquals(List.of(rootProperty), child.getHierarchyJobProperties());
+ var defaultSpec = new WorkspaceSpec();
+ defaultSpec.setName("dev");
+ var rootSpec = new WorkspaceSpec();
+ rootSpec.setName("dev");
+ var extraSpec = new WorkspaceSpec();
+ extraSpec.setName("extra");
+ defaults.getWorkspaceSpecs().add(defaultSpec);
+ defaults.getWorkspaceSpecs().add(extraSpec);
+ root.getWorkspaceSpecs().add(rootSpec);
+ assertEquals(List.of(rootSpec, extraSpec), child.getHierarchyWorkspaceSpecs());
+ }
+
+ @Test
+ void defaultAssigneesAreCheckedAgainstTheTargetProject() {
+ var users = mock(UserService.class);
+ var user = mock(User.class);
+ oneDev.when(() -> OneDev.getInstance(UserService.class)).thenReturn(users);
+ when(users.findByName("reviewer")).thenReturn(user);
+ defaults.getPullRequestSetting().setDefaultAssignees(new ArrayList<>(List.of("reviewer")));
+ try (var security = mockStatic(SecurityUtils.class)) {
+ security.when(() -> SecurityUtils.canWriteCode(user.asSubject(), child)).thenReturn(true);
+ assertEquals(List.of(user), child.findDefaultPullRequestAssignees());
+ security.when(() -> SecurityUtils.canWriteCode(user.asSubject(), child)).thenReturn(false);
+ assertThrows(io.onedev.commons.utils.ExplicitException.class, child::findDefaultPullRequestAssignees);
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/notification/ProjectDefaultsNotificationTest.java b/server-core/src/test/java/io/onedev/server/notification/ProjectDefaultsNotificationTest.java
new file mode 100644
index 0000000000..bec8749ffa
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/notification/ProjectDefaultsNotificationTest.java
@@ -0,0 +1,70 @@
+package io.onedev.server.notification;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.http.client.methods.HttpPost;
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.event.project.ProjectEvent;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.support.channelnotification.ChannelNotification;
+import io.onedev.server.model.support.channelnotification.ChannelNotificationSetting;
+import io.onedev.server.service.ProjectService;
+
+public class ProjectDefaultsNotificationTest {
+
+ private static class NotificationManager extends ChannelNotificationManager<ChannelNotificationSetting> {
+ @Override
+ protected void post(HttpPost post, String title, ProjectEvent event) {
+ fail("This test must not send notifications");
+ }
+ }
+
+ @Test
+ void integrationsInheritDefaultsAndOverrideDuplicateWebhookUrls() throws Exception {
+ var defaults = new Project();
+ defaults.setId(Project.DEFAULT_ID);
+ var root = new Project();
+ root.setId(1L);
+ var child = new Project();
+ child.setId(2L);
+ child.setParent(root);
+ var defaultNotification = new ChannelNotification();
+ defaultNotification.setWebhookUrl("https://example.invalid/default");
+ var overriddenNotification = new ChannelNotification();
+ overriddenNotification.setWebhookUrl("https://example.invalid/override");
+ var childNotification = new ChannelNotification();
+ childNotification.setWebhookUrl(overriddenNotification.getWebhookUrl());
+ var defaultSettings = new ChannelNotificationSetting();
+ defaultSettings.setNotifications(List.of(defaultNotification, overriddenNotification));
+ defaults.setContributedSetting(ChannelNotificationSetting.class, defaultSettings);
+ root.setContributedSetting(ChannelNotificationSetting.class, new ChannelNotificationSetting());
+ var childSettings = new ChannelNotificationSetting();
+ childSettings.setNotifications(List.of(childNotification));
+ child.setContributedSetting(ChannelNotificationSetting.class, childSettings);
+ var method = ChannelNotificationManager.class.getDeclaredMethod("getNotifications", Project.class);
+ method.setAccessible(true);
+ try (var oneDev = mockStatic(OneDev.class)) {
+ var subscription = mock(SubscriptionService.class);
+ var projects = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(subscription);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ when(subscription.isSubscriptionActive()).thenReturn(true);
+ var notifications = (Collection<?>) method.invoke(new NotificationManager(), child);
+ assertEquals(2, notifications.size());
+ assertTrue(notifications.contains(defaultNotification));
+ assertTrue(notifications.contains(childNotification));
+ assertFalse(notifications.contains(overriddenNotification));
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ notifications = (Collection<?>) method.invoke(new NotificationManager(), child);
+ assertEquals(List.of(childNotification), List.copyOf(notifications));
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/rest/ProjectReferenceSecurityTest.java b/server-core/src/test/java/io/onedev/server/rest/ProjectReferenceSecurityTest.java
new file mode 100644
index 0000000000..64cb898074
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/rest/ProjectReferenceSecurityTest.java
@@ -0,0 +1,59 @@
+package io.onedev.server.rest;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import org.apache.shiro.authz.UnauthorizedException;
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+
+import io.onedev.commons.loader.AppLoader;
+import io.onedev.server.model.*;
+import io.onedev.server.persistence.dao.Dao;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperModule;
+import io.onedev.server.web.util.WicketUtils;
+
+class ProjectReferenceSecurityTest {
+
+ @Test
+ void jsonProjectReferencesRejectDefaultsExceptAdministratorAuthorizations() throws Exception {
+ var dao = mock(Dao.class);
+ var defaults = new Project(); defaults.setId(Project.DEFAULT_ID);
+ var ordinary = new Project(); ordinary.setId(1L);
+ when(dao.load(Project.class, Project.DEFAULT_ID)).thenReturn(defaults);
+ when(dao.load(Project.class, 1L)).thenReturn(ordinary);
+ var mapper = JsonMapper.builder()
+ .visibility(PropertyAccessor.ALL, Visibility.NONE)
+ .visibility(PropertyAccessor.FIELD, Visibility.ANY)
+ .addModule(new HibernateObjectMapperModule(dao)).build();
+ try (var loader = mockStatic(AppLoader.class); var security = mockStatic(SecurityUtils.class);
+ var wicket = mockStatic(WicketUtils.class)) {
+ loader.when(() -> AppLoader.getInstance(Dao.class)).thenReturn(dao);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ for (var type: new Class<?>[] {UserAuthorization.class, GroupAuthorization.class,
+ BaseAuthorization.class, AccessTokenAuthorization.class}) {
+ var error = assertThrows(JsonMappingException.class, () -> mapper.readValue("{\"projectId\":-1}", type));
+ assertInstanceOf(UnauthorizedException.class, error.getCause());
+ }
+ verify(dao, never()).load(eq(Project.class), anyLong());
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ assertSame(defaults, mapper.readValue("{\"projectId\":-1}", UserAuthorization.class).getProject());
+ assertSame(defaults, mapper.readValue("{\"projectId\":-1}", GroupAuthorization.class).getProject());
+ assertSame(defaults, mapper.readValue("{\"projectId\":-1}", BaseAuthorization.class).getProject());
+ assertSame(defaults, mapper.readValue("{\"projectId\":-1}", AccessTokenAuthorization.class).getProject());
+ clearInvocations(dao);
+ for (var type: new Class<?>[] {Iteration.class, ProjectLabel.class})
+ assertThrows(JsonMappingException.class, () -> mapper.readValue("{\"projectId\":-1}", type));
+ assertThrows(JsonMappingException.class, () -> mapper.readValue("{\"targetProjectId\":-1}", PullRequest.class));
+ assertThrows(JsonMappingException.class, () -> mapper.readValue("{\"projectId\":-2}", UserAuthorization.class));
+ verify(dao, never()).load(eq(Project.class), anyLong());
+ security.when(SecurityUtils::isAdministrator).thenReturn(false);
+ assertSame(ordinary, mapper.readValue("{\"projectId\":1}", Iteration.class).getProject());
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/rest/resource/ProjectDefaultsRestTest.java b/server-core/src/test/java/io/onedev/server/rest/resource/ProjectDefaultsRestTest.java
new file mode 100644
index 0000000000..685756db0a
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/rest/resource/ProjectDefaultsRestTest.java
@@ -0,0 +1,362 @@
+package io.onedev.server.rest.resource;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.List;
+import java.util.Set;
+
+import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.PathParam;
+
+import org.apache.shiro.authz.UnauthorizedException;
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
+
+import io.onedev.commons.loader.ImplementationRegistry;
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.data.migration.VersionedXmlDoc;
+import io.onedev.server.exception.NoSubscriptionException;
+import io.onedev.server.model.*;
+import io.onedev.server.model.support.build.JobProperty;
+import io.onedev.server.model.support.build.NamedBuildQuery;
+import io.onedev.server.model.support.pullrequest.MergeStrategy;
+import io.onedev.server.model.support.workspace.spec.WorkspaceSpec;
+import io.onedev.server.model.support.workspace.spec.shell.PosixShell;
+import io.onedev.server.model.support.workspace.spec.shell.WorkspaceShell;
+import io.onedev.server.persistence.TransactionService;
+import io.onedev.server.rest.resource.support.ProjectDefaults;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.*;
+import io.onedev.server.util.jackson.ObjectMapperProvider;
+import io.onedev.server.validation.HibernateValidationTestSupport;
+import io.onedev.server.web.util.WicketUtils;
+
+class ProjectDefaultsRestTest extends HibernateValidationTestSupport {
+
+ private ObjectMapper newObjectMapper() {
+ var implementations = mock(ImplementationRegistry.class);
+ when(implementations.getImplementations(WorkspaceShell.class)).thenReturn(List.of(PosixShell.class));
+ return new ObjectMapperProvider(Set.of(), Set.of(), implementations, Set.of()).get();
+ }
+
+ @Test
+ void defaultsJsonExcludesUnsupportedSettingsWithoutChangingOrdinaryProjectSettings() throws Exception {
+ var project = new Project();
+ project.getBuildSetting().setNamedQueries(List.of(new NamedBuildQuery("Recent", null)));
+ var mapper = newObjectMapper();
+ var defaults = mapper.readTree(mapper.writeValueAsString(ProjectDefaults.from(project)));
+ var ordinary = mapper.readTree(mapper.writeValueAsString(ProjectResource.ProjectSetting.from(project)));
+ assertFalse(defaults.has("defaultRoleIds"));
+ assertFalse(defaults.has("defaultRoles"));
+ assertFalse(defaults.has("gitPackConfig"));
+ var ordinaryData = mapper.readTree(mapper.writeValueAsString(ProjectResource.ProjectData.from(project)));
+ assertTrue(ordinaryData.has("gitPackConfig"));
+ for (var name: List.of("packSetting", "workspaceSetting", "namedCommitQueries", "namedCodeCommentQueries")) {
+ assertFalse(defaults.has(name), name);
+ assertTrue(ordinary.has(name), name);
+ }
+ for (var name: List.of("listFields", "listLinks", "boardSpecs", "namedQueries", "transitionSpecs", "timesheetSettings")) {
+ assertFalse(defaults.get("issueSetting").has(name), name);
+ assertTrue(ordinary.get("issueSetting").has(name), name);
+ }
+ for (var name: List.of("listParams", "namedQueries")) {
+ assertFalse(defaults.get("buildSetting").has(name), name);
+ assertTrue(ordinary.get("buildSetting").has(name), name);
+ }
+ assertFalse(defaults.get("pullRequestSetting").has("namedQueries"));
+ assertTrue(ordinary.get("pullRequestSetting").has("namedQueries"));
+ }
+
+ @Test
+ void defaultsJsonRejectsUnsupportedSettings() {
+ var mapper = newObjectMapper();
+ for (var name: List.of("defaultRoles", "defaultRoleIds", "gitPackConfig", "packSetting", "workspaceSetting", "namedCommitQueries", "namedCodeCommentQueries"))
+ assertThrows(UnrecognizedPropertyException.class,
+ () -> mapper.readValue("{\"" + name + "\":null}", ProjectDefaults.class), name);
+ for (var name: List.of("listFields", "listLinks", "boardSpecs", "namedQueries", "transitionSpecs", "timesheetSettings"))
+ assertThrows(UnrecognizedPropertyException.class,
+ () -> mapper.readValue("{\"issueSetting\":{\"" + name + "\":null}}", ProjectDefaults.class), name);
+ for (var name: List.of("listParams", "namedQueries"))
+ assertThrows(UnrecognizedPropertyException.class,
+ () -> mapper.readValue("{\"buildSetting\":{\"" + name + "\":null}}", ProjectDefaults.class), name);
+ assertThrows(UnrecognizedPropertyException.class,
+ () -> mapper.readValue("{\"pullRequestSetting\":{\"namedQueries\":[]}}", ProjectDefaults.class));
+ }
+
+ @Test
+ void supportedDefaultsRoundTripThroughJsonAndPreserveExcludedSettings() throws Exception {
+ var source = new Project();
+ source.getBuildSetting().setCachePreserveDays(30);
+ var property = new JobProperty();
+ property.setName("image");
+ property.setValue("alpine");
+ source.getBuildSetting().getJobProperties().add(property);
+ source.getIssueSetting().setBranchPrefix("ticket");
+ source.getPullRequestSetting().setDefaultMergeStrategy(MergeStrategy.SQUASH_SOURCE_BRANCH_COMMITS);
+ source.getPullRequestSetting().setDefaultAssignees(List.of("reviewer"));
+ source.getPullRequestSetting().setDeleteSourceBranchAfterMerge(true);
+ var mapper = newObjectMapper();
+ var defaults = mapper.readValue(mapper.writeValueAsString(ProjectDefaults.from(source)), ProjectDefaults.class);
+ assertPaths(validator.validate(defaults));
+ var target = new Project();
+ var queries = List.of(new NamedBuildQuery("Existing", null));
+ target.getBuildSetting().setNamedQueries(queries);
+ var gitPackConfig = target.getGitPackConfig();
+ gitPackConfig.setThreads("3");
+ var packSetting = target.getPackSetting();
+ var workspaceSetting = target.getWorkspaceSetting();
+ defaults.populate(target);
+ assertEquals(30, target.getBuildSetting().getCachePreserveDays());
+ assertEquals("alpine", target.getBuildSetting().getJobProperties().get(0).getValue());
+ assertEquals("ticket", target.getIssueSetting().getBranchPrefix());
+ assertEquals(MergeStrategy.SQUASH_SOURCE_BRANCH_COMMITS, target.getPullRequestSetting().getDefaultMergeStrategy());
+ assertEquals(List.of("reviewer"), target.getPullRequestSetting().getDefaultAssignees());
+ assertTrue(target.getPullRequestSetting().getDeleteSourceBranchAfterMerge());
+ assertSame(queries, target.getBuildSetting().getNamedQueries());
+ assertSame(gitPackConfig, target.getGitPackConfig());
+ assertEquals("3", target.getGitPackConfig().getThreads());
+ assertSame(packSetting, target.getPackSetting());
+ assertSame(workspaceSetting, target.getWorkspaceSetting());
+ }
+
+ private void inject(Object target, String name, Object value) throws Exception {
+ var field = target.getClass().getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(target, value);
+ }
+
+ @Test
+ void everyProjectAndRepositoryIdEndpointRejectsNegativeIdsBeforeLoading() throws Exception {
+ var projects = mock(ProjectService.class);
+ int checked = 0;
+ for (var resource: List.of(new ProjectResource(), new RepositoryResource())) {
+ inject(resource, "projectService", projects);
+ for (var method: resource.getClass().getDeclaredMethods()) {
+ var parameters = method.getParameters();
+ if (parameters.length != 0 && parameters[0].isAnnotationPresent(PathParam.class)
+ && parameters[0].getAnnotation(PathParam.class).value().equals("projectId")) {
+ var args = new Object[parameters.length];
+ args[0] = Project.DEFAULT_ID;
+ for (int i = 1; i < args.length; i++) {
+ if (parameters[i].getType() == int.class)
+ args[i] = 0;
+ else if (parameters[i].getType() == boolean.class)
+ args[i] = false;
+ }
+ var exception = assertThrows(InvocationTargetException.class, () -> method.invoke(resource, args), method.getName());
+ assertInstanceOf(NotFoundException.class, exception.getCause(), method.getName());
+ checked++;
+ }
+ }
+ }
+ assertTrue(checked >= 25);
+ verifyNoInteractions(projects);
+ }
+
+ @Test
+ void parentAndForkReferencesCannotTargetDefaults() {
+ var projects = mock(ProjectService.class);
+ var project = new Project();
+ for (boolean parent: List.of(true, false)) {
+ var data = new ProjectResource.ProjectData();
+ if (parent)
+ data.setParentId(Project.DEFAULT_ID);
+ else
+ data.setForkedFromId(Project.DEFAULT_ID);
+ assertThrows(NotFoundException.class, () -> data.populate(project, projects));
+ }
+ verifyNoInteractions(projects);
+ }
+
+ @Test
+ void normalProjectSettingsRemainAccessibleToTheirManager() throws Exception {
+ var projects = mock(ProjectService.class);
+ var project = new Project(); project.setId(1L);
+ when(projects.load(1L)).thenReturn(project);
+ var resource = new ProjectResource(); inject(resource, "projectService", projects);
+ try (var security = mockStatic(SecurityUtils.class)) {
+ security.when(() -> SecurityUtils.canManageProject(project)).thenReturn(true);
+ assertSame(project.getBuildSetting(), resource.getSetting(1L).getBuildSetting());
+ }
+ }
+
+ @Test
+ void defaultsRequireAdministratorAndActiveSubscriptionBeforeLoading() throws Exception {
+ var projects = mock(ProjectService.class);
+ var resource = new SettingResource(mock(SettingService.class), mock(AuditService.class), validator);
+ inject(resource, "projectService", projects);
+ try (var security = mockStatic(SecurityUtils.class); var wicket = mockStatic(WicketUtils.class)) {
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertThrows(UnauthorizedException.class, resource::getProjectDefaults);
+ assertThrows(UnauthorizedException.class, () -> resource.setProjectDefaults(new ProjectDefaults()));
+ assertThrows(UnauthorizedException.class, resource::getProjectDefaultUserAuthorizations);
+ assertThrows(UnauthorizedException.class, resource::getProjectDefaultGroupAuthorizations);
+ assertThrows(UnauthorizedException.class, resource::getProjectDefaultBaseAuthorizations);
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ assertThrows(NoSubscriptionException.class, resource::getProjectDefaults);
+ assertThrows(NoSubscriptionException.class, () -> resource.setProjectDefaults(new ProjectDefaults()));
+ assertThrows(NoSubscriptionException.class, resource::getProjectDefaultBaseAuthorizations);
+ verifyNoInteractions(projects);
+ }
+ }
+
+ @Test
+ void administratorsCanRoundTripAllDefaultsWithoutChangingProjectIdentity() throws Exception {
+ var projects = mock(ProjectService.class);
+ var project = new Project(); project.setId(Project.DEFAULT_ID); project.setName(Project.DEFAULT_NAME);
+ project.getGitPackConfig().setThreads("2");
+ project.getCodeIndexingSetting().setAnalyzeFiles("**.java");
+ project.getAiSetting().setExcludedReviewFiles("vendor/**");
+ var spec = new WorkspaceSpec(); spec.setName("dev"); project.getWorkspaceSpecs().add(spec);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(project);
+ var audit = mock(AuditService.class);
+ var resource = new SettingResource(mock(SettingService.class), audit, validator);
+ inject(resource, "projectService", projects);
+ var role = new Role(); role.setId(5L); role.setName("Reader");
+ var transactions = mock(TransactionService.class);
+ doAnswer(invocation -> {
+ invocation.getArgument(0, Runnable.class).run();
+ return null;
+ }).when(transactions).run(any());
+ inject(resource, "transactionService", transactions);
+ var authorization = new BaseAuthorization(); authorization.setRole(role); authorization.setProject(project);
+ project.getBaseAuthorizations().add(authorization);
+ try (var security = mockStatic(SecurityUtils.class); var wicket = mockStatic(WicketUtils.class);
+ var xml = mockStatic(VersionedXmlDoc.class)) {
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ var document = mock(VersionedXmlDoc.class); when(document.toXML()).thenReturn("audit");
+ xml.when(() -> VersionedXmlDoc.fromBean(any())).thenReturn(document);
+ var defaults = resource.getProjectDefaults();
+ assertEquals("**.java", defaults.getCodeIndexingSetting().getAnalyzeFiles());
+ assertEquals("vendor/**", defaults.getAiSetting().getExcludedReviewFiles());
+ assertEquals(List.of(spec), defaults.getWorkspaceSpecs());
+ var mapper = newObjectMapper();
+ defaults = mapper.readValue(mapper.writeValueAsString(defaults), ProjectDefaults.class);
+ try (var response = resource.setProjectDefaults(defaults)) {
+ assertEquals(200, response.getStatus());
+ }
+ assertEquals(List.of(authorization), List.copyOf(project.getBaseAuthorizations()));
+ defaults = new ProjectDefaults();
+ defaults.getIssueSetting().setBranchPrefix("issue-");
+ try (var response = resource.setProjectDefaults(defaults)) {
+ assertEquals(200, response.getStatus());
+ }
+ assertEquals("2", project.getGitPackConfig().getThreads());
+ assertEquals("issue-", project.getIssueSetting().getBranchPrefix());
+ assertEquals(Project.DEFAULT_ID, project.getId());
+ assertEquals(Project.DEFAULT_NAME, project.getName());
+ assertNull(project.getParent());
+ assertEquals(List.of(authorization), List.copyOf(resource.getProjectDefaultBaseAuthorizations()));
+ verify(projects, times(2)).update(project);
+ verify(audit, times(2)).audit(eq(project), anyString(), eq("audit"), eq("audit"));
+ verify(transactions, times(2)).run(any());
+ }
+ }
+
+ @Test
+ void defaultsValidateRequiredContainersAndNestedSettings() {
+ var defaults = new ProjectDefaults();
+ assertPaths(validator.validate(defaults));
+ defaults.setAiSetting(null);
+ defaults.setBuildSetting(null);
+ defaults.setBranchProtections(null);
+ assertPaths(validator.validate(defaults), "aiSetting", "buildSetting", "branchProtections");
+ defaults = new ProjectDefaults();
+ var property = new JobProperty(); property.setName("");
+ defaults.getBuildSetting().getJobProperties().add(property);
+ assertFalse(validator.validate(defaults).isEmpty());
+ }
+
+ @Test
+ void defaultsAuthorizationsDoNotTrustInheritedManagementPermission() throws Exception {
+ var project = new Project(); project.setId(Project.DEFAULT_ID);
+ var userAuth = new UserAuthorization(); userAuth.setProject(project);
+ var groupAuth = new GroupAuthorization(); groupAuth.setProject(project);
+ var baseAuth = new BaseAuthorization(); baseAuth.setProject(project);
+ var users = mock(UserAuthorizationService.class); when(users.load(1L)).thenReturn(userAuth);
+ var groups = mock(GroupAuthorizationService.class); when(groups.load(1L)).thenReturn(groupAuth);
+ var bases = mock(BaseAuthorizationService.class); when(bases.load(1L)).thenReturn(baseAuth);
+ var audit = mock(AuditService.class);
+ var userResource = new UserAuthorizationResource(users, audit);
+ var groupResource = new GroupAuthorizationResource(groups, audit);
+ var baseResource = new BaseAuthorizationResource(bases, audit);
+ try (var security = mockStatic(SecurityUtils.class); var wicket = mockStatic(WicketUtils.class)) {
+ security.when(() -> SecurityUtils.canManageProject(project)).thenReturn(true);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertThrows(UnauthorizedException.class, () -> userResource.createAuthorization(userAuth));
+ assertThrows(UnauthorizedException.class, () -> groupResource.createAuthorization(groupAuth));
+ assertThrows(UnauthorizedException.class, () -> baseResource.createAuthorization(baseAuth));
+ assertThrows(UnauthorizedException.class, () -> userResource.deleteAuthorization(1L));
+ assertThrows(UnauthorizedException.class, () -> groupResource.deleteAuthorization(1L));
+ assertThrows(UnauthorizedException.class, () -> baseResource.deleteAuthorization(1L));
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ assertSame(userAuth, userResource.getAuthorization(1L));
+ assertSame(groupAuth, groupResource.getAuthorization(1L));
+ assertSame(baseAuth, baseResource.getAuthorization(1L));
+ verify(users, never()).createOrUpdate(any());
+ verify(groups, never()).createOrUpdate(any());
+ verify(bases, never()).create(any());
+ verifyNoInteractions(audit);
+ }
+ }
+ @Test
+ void invalidDefaultsDoNotOverwriteStoredSettings() throws Exception {
+ var projects = mock(ProjectService.class);
+ var project = new Project(); project.setId(Project.DEFAULT_ID);
+ project.getCodeIndexingSetting().setAnalyzeFiles("**.java");
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(project);
+ var audit = mock(AuditService.class);
+ var resource = new SettingResource(mock(SettingService.class), audit, validator);
+ inject(resource, "projectService", projects);
+ var transactions = mock(TransactionService.class);
+ inject(resource, "transactionService", transactions);
+ try (var security = mockStatic(SecurityUtils.class); var wicket = mockStatic(WicketUtils.class)) {
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ var defaults = new ProjectDefaults(); defaults.setCodeIndexingSetting(null);
+ assertThrows(ExplicitException.class, () -> resource.setProjectDefaults(defaults));
+ var nullElements = new ProjectDefaults();
+ nullElements.getWorkspaceSpecs().add(null);
+ nullElements.getBuildSetting().getJobSecrets().add(null);
+ assertPaths(validator.validate(nullElements), "workspaceSpecs[0].<list element>",
+ "buildSetting.jobSecrets[0].<list element>");
+ assertThrows(ExplicitException.class, () -> resource.setProjectDefaults(nullElements));
+ var duplicateSpecs = new ProjectDefaults();
+ var firstSpec = new WorkspaceSpec(); firstSpec.setName("dev");
+ var secondSpec = new WorkspaceSpec(); secondSpec.setName("dev");
+ secondSpec.setDescription("Different configuration with the same name");
+ duplicateSpecs.getWorkspaceSpecs().addAll(List.of(firstSpec, secondSpec));
+ assertPaths(validator.validate(duplicateSpecs), "workspaceSpecs");
+ assertEquals("workspaceSpecs: Workspace spec names must be unique",
+ assertThrows(ExplicitException.class, () -> resource.setProjectDefaults(duplicateSpecs)).getMessage());
+ assertEquals("**.java", project.getCodeIndexingSetting().getAnalyzeFiles());
+ assertTrue(project.getWorkspaceSpecs().isEmpty());
+ verify(projects, never()).update(any());
+ verifyNoInteractions(audit, transactions);
+ secondSpec.setName("Dev");
+ assertPaths(validator.validate(duplicateSpecs));
+ }
+ }
+
+ @Test
+ void administratorsCanReadDefaultAuthorizations() throws Exception {
+ var project = new Project(); project.setId(Project.DEFAULT_ID);
+ var projects = mock(ProjectService.class); when(projects.load(Project.DEFAULT_ID)).thenReturn(project);
+ var resource = new SettingResource(mock(SettingService.class), mock(AuditService.class), validator);
+ inject(resource, "projectService", projects);
+ try (var security = mockStatic(SecurityUtils.class); var wicket = mockStatic(WicketUtils.class)) {
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertSame(project.getUserAuthorizations(), resource.getProjectDefaultUserAuthorizations());
+ assertSame(project.getGroupAuthorizations(), resource.getProjectDefaultGroupAuthorizations());
+ assertSame(project.getBaseAuthorizations(), resource.getProjectDefaultBaseAuthorizations());
+ }
+ }
+
+}
diff --git a/server-core/src/test/java/io/onedev/server/security/AccessTokenRevocationTest.java b/server-core/src/test/java/io/onedev/server/security/AccessTokenRevocationTest.java
new file mode 100644
index 0000000000..9dde41c896
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/security/AccessTokenRevocationTest.java
@@ -0,0 +1,199 @@
+package io.onedev.server.security;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.shiro.authz.Permission;
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.ThreadContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.model.AccessToken;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.BaseAuthorization;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.ProjectLastActivityDate;
+import io.onedev.server.model.Role;
+import io.onedev.server.model.User;
+import io.onedev.server.model.support.administration.GlobalIssueSetting;
+import io.onedev.server.security.permission.AccessProject;
+import io.onedev.server.security.permission.ProjectPermission;
+import io.onedev.server.service.AccessTokenService;
+import io.onedev.server.service.BaseAuthorizationService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.util.facade.ProjectCache;
+
+class AccessTokenRevocationTest {
+
+ private MockedStatic<OneDev> oneDev;
+ private Subject previousSubject;
+ private Subject tokenSubject;
+ private AccessToken token;
+ private Role role;
+ private Project defaults;
+ private Project root;
+ private Project child;
+ private Project other;
+ private ProjectCache cache;
+ private BaseAuthorizationService baseAuthorizations;
+ private final Set<Long> managedProjectIds = new HashSet<>();
+ private static final Map<String, Collection<String>> REPORTS = Map.of("build", List.of("coverage"));
+
+ @BeforeEach
+ void setUp() {
+ previousSubject = ThreadContext.getSubject();
+ oneDev = mockStatic(OneDev.class);
+ var subscription = mock(SubscriptionService.class);
+ oneDev.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(subscription);
+ when(subscription.isSubscriptionActive()).thenReturn(true);
+ var settings = mock(SettingService.class);
+ oneDev.when(() -> OneDev.getInstance(SettingService.class)).thenReturn(settings);
+ when(settings.getIssueSetting()).thenReturn(new GlobalIssueSetting());
+ defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ root = project(1L, "root");
+ child = project(2L, "root/child");
+ child.setParent(root);
+ other = project(3L, "other");
+ var projects = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ cache = new ProjectCache(new HashMap<>());
+ for (var project: List.of(root, child, other)) {
+ cache.put(project.getId(), project.getFacade());
+ when(projects.load(project.getId())).thenReturn(project);
+ }
+ baseAuthorizations = mock(BaseAuthorizationService.class);
+ oneDev.when(() -> OneDev.getInstance(BaseAuthorizationService.class)).thenReturn(baseAuthorizations);
+ var ownerSubject = mock(Subject.class);
+ when(ownerSubject.isPermitted(any(Permission.class))).thenAnswer(it -> {
+ var permission = (ProjectPermission) it.getArgument(0);
+ return managedProjectIds.contains(permission.getProject().getId());
+ });
+ var owner = spy(new User());
+ owner.setId(100L);
+ owner.setName("owner");
+ doReturn(ownerSubject).when(owner).asSubject();
+ token = new AccessToken();
+ token.setId(10L);
+ token.setOwner(owner);
+ var tokens = mock(AccessTokenService.class);
+ oneDev.when(() -> OneDev.getInstance(AccessTokenService.class)).thenReturn(tokens);
+ when(tokens.get(token.getId())).thenReturn(token);
+ tokenSubject = mock(Subject.class);
+ when(tokenSubject.getPrincipal()).thenReturn(SecurityUtils.asAccessTokenPrincipal(token.getId()));
+ ThreadContext.bind(tokenSubject);
+ role = new Role();
+ role.setId(1L);
+ role.setName("manager");
+ role.setManageProject(true);
+ }
+
+ @AfterEach
+ void tearDown() {
+ ThreadContext.unbindSubject();
+ if (previousSubject != null)
+ ThreadContext.bind(previousSubject);
+ oneDev.close();
+ }
+
+ private Project project(Long id, String path) {
+ var project = new Project();
+ project.setId(id);
+ project.setName(path);
+ project.setPath(path);
+ project.setLastActivityDate(new ProjectLastActivityDate());
+ return project;
+ }
+
+ private void grant(Project project) {
+ var authorization = new AccessTokenAuthorization();
+ authorization.setProject(project);
+ authorization.setRole(role);
+ authorization.setToken(token);
+ token.getAuthorizations().add(authorization);
+ }
+
+ private void assertAccess(Project project, boolean expected) {
+ assertEquals(expected, SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject()).contains(project),
+ "project enumeration: " + project.getPath());
+ assertEquals(expected, SecurityUtils.isAssignedRole(tokenSubject, project, role),
+ "role assignment: " + project.getPath());
+ var reports = SecurityUtils.getAccessibleReportNames(project, Object.class, REPORTS);
+ assertEquals(expected, reports.containsKey("build"), "report access: " + project.getPath());
+ if (expected)
+ assertEquals(Set.of("coverage"), new HashSet<>(reports.get("build")));
+ }
+
+ @Test
+ void revokingOwnerManagementInvalidatesSavedTokenGrants() {
+ grant(root);
+ managedProjectIds.add(root.getId());
+ assertAccess(root, true);
+ assertAccess(child, true);
+ assertAccess(other, false);
+
+ managedProjectIds.clear();
+ assertAccess(root, false);
+ assertAccess(child, false);
+ assertEquals(1, token.getAuthorizations().size());
+
+ managedProjectIds.add(root.getId());
+ assertAccess(child, true);
+ }
+
+ @Test
+ void managingChildDoesNotValidateARevokedParentGrant() {
+ grant(root);
+ managedProjectIds.add(child.getId());
+ assertAccess(root, false);
+ assertAccess(child, false);
+ }
+
+ @Test
+ void revocationDoesNotDiscardOtherValidTokenGrants() {
+ grant(root);
+ grant(other);
+ managedProjectIds.add(other.getId());
+ assertAccess(root, false);
+ assertAccess(child, false);
+ assertAccess(other, true);
+ }
+
+ @Test
+ void independentlyGrantedDefaultRoleRemainsEffective() {
+ grant(root);
+ var authorization = new BaseAuthorization();
+ authorization.setProject(root);
+ authorization.setRole(role);
+ root.getBaseAuthorizations().add(authorization);
+ role.getBaseAuthorizations().add(authorization);
+ when(baseAuthorizations.query()).thenReturn(List.of(authorization));
+ assertAccess(root, true);
+ assertAccess(child, true);
+ assertAccess(other, false);
+ }
+
+ @Test
+ void legacyDefaultsTokenGrantAlsoRequiresOwnerManagement() {
+ grant(defaults);
+ managedProjectIds.add(defaults.getId());
+ assertAccess(root, true);
+ assertAccess(other, true);
+ managedProjectIds.clear();
+ assertAccess(root, false);
+ assertAccess(other, false);
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/security/AuthorizationInfoCacheTest.java b/server-core/src/test/java/io/onedev/server/security/AuthorizationInfoCacheTest.java
new file mode 100644
index 0000000000..19a8b75c5a
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/security/AuthorizationInfoCacheTest.java
@@ -0,0 +1,418 @@
+package io.onedev.server.security;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.apache.shiro.mgt.DefaultSecurityManager;
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.ThreadContext;
+import org.apache.wicket.MetaDataKey;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.model.AccessToken;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.ProjectLastActivityDate;
+import io.onedev.server.model.Role;
+import io.onedev.server.model.User;
+import io.onedev.server.model.UserAuthorization;
+import io.onedev.server.model.support.administration.GlobalIssueSetting;
+import io.onedev.server.model.support.administration.SecuritySetting;
+import io.onedev.server.model.support.role.JobPrivilege;
+import io.onedev.server.persistence.SessionService;
+import io.onedev.server.security.permission.AccessProject;
+import io.onedev.server.security.permission.ManageProject;
+import io.onedev.server.security.permission.ProjectPermission;
+import io.onedev.server.security.permission.SystemAdministration;
+import io.onedev.server.service.AccessTokenService;
+import io.onedev.server.service.BaseAuthorizationService;
+import io.onedev.server.service.IssueAuthorizationService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.service.UserService;
+import io.onedev.server.util.facade.ProjectCache;
+
+class AuthorizationInfoCacheTest {
+
+ private MockedStatic<OneDev> oneDev;
+ private Subject previousSubject;
+ private DefaultAuthorizingService authorizing;
+ private DefaultSecurityManager securityManager;
+ private IssueAuthorizationService issueAuthorizations;
+ private UserService users;
+ private AccessTokenService tokens;
+ private SubscriptionService subscription;
+ private User owner;
+ private AccessToken token;
+ private Subject tokenSubject;
+ private Role role;
+ private ProjectCache cache;
+ private final List<Project> projects = new ArrayList<>();
+
+ @BeforeEach
+ void setUp() throws Exception {
+ assertNull(AuthorizationInfoCache.get());
+ assertNull(RequestCycle.get());
+ previousSubject = ThreadContext.getSubject();
+ oneDev = mockStatic(OneDev.class);
+ subscription = mock(SubscriptionService.class);
+ when(subscription.isSubscriptionActive()).thenReturn(true);
+ oneDev.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(subscription);
+ var settings = mock(SettingService.class);
+ when(settings.getIssueSetting()).thenReturn(new GlobalIssueSetting());
+ when(settings.getSecuritySetting()).thenReturn(new SecuritySetting());
+ oneDev.when(() -> OneDev.getInstance(SettingService.class)).thenReturn(settings);
+ var projectService = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projectService);
+ var defaults = project(Project.DEFAULT_ID);
+ when(projectService.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ oneDev.when(() -> OneDev.getInstance(BaseAuthorizationService.class))
+ .thenReturn(mock(BaseAuthorizationService.class));
+ users = mock(UserService.class);
+ oneDev.when(() -> OneDev.getInstance(UserService.class)).thenReturn(users);
+ owner = spy(new User());
+ owner.setId(100L);
+ owner.setName("owner");
+ when(users.get(owner.getId())).thenReturn(owner);
+ role = new Role();
+ role.setId(1L);
+ role.setName("manager");
+ role.setManageProject(true);
+ grantOwner(defaults);
+ token = new AccessToken();
+ token.setId(1L);
+ token.setOwner(owner);
+ tokens = mock(AccessTokenService.class);
+ when(tokens.get(token.getId())).thenReturn(token);
+ oneDev.when(() -> OneDev.getInstance(AccessTokenService.class)).thenReturn(tokens);
+ cache = new ProjectCache(new HashMap<>());
+ for (long id = 1; id <= 100; id++) {
+ var project = project(id);
+ projects.add(project);
+ cache.put(id, project.getFacade());
+ when(projectService.load(id)).thenReturn(project);
+ var authorization = new AccessTokenAuthorization();
+ authorization.setToken(token);
+ authorization.setProject(project);
+ authorization.setRole(role);
+ token.getAuthorizations().add(authorization);
+ }
+ var sessions = mock(SessionService.class);
+ when(sessions.call(any())).thenAnswer(it -> ((Callable<?>) it.getArgument(0)).call());
+ issueAuthorizations = mock(IssueAuthorizationService.class);
+ authorizing = new DefaultAuthorizingService();
+ inject("sessionService", sessions);
+ inject("settingService", settings);
+ inject("issueAuthorizationService", issueAuthorizations);
+ securityManager = new DefaultSecurityManager(authorizing);
+ var ownerSubject = new Subject.Builder(securityManager).principals(owner.getPrincipals()).buildSubject();
+ doReturn(ownerSubject).when(owner).asSubject();
+ tokenSubject = newTokenSubject();
+ ThreadContext.bind(tokenSubject);
+ }
+
+ @AfterEach
+ void tearDown() {
+ ThreadContext.unbindSubject();
+ if (previousSubject != null)
+ ThreadContext.bind(previousSubject);
+ if (securityManager != null)
+ securityManager.destroy();
+ if (oneDev != null)
+ oneDev.close();
+ assertNull(AuthorizationInfoCache.get());
+ }
+
+ private void inject(String name, Object value) throws Exception {
+ var field = DefaultAuthorizingService.class.getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(authorizing, value);
+ }
+
+ private Project project(Long id) {
+ var project = new Project();
+ project.setId(id);
+ project.setName("project" + id);
+ project.setPath(project.getName());
+ project.setLastActivityDate(new ProjectLastActivityDate());
+ return project;
+ }
+
+ private void grantOwner(Project project) {
+ var authorization = new UserAuthorization();
+ authorization.setProject(project);
+ authorization.setUser(owner);
+ authorization.setRole(role);
+ owner.getProjectAuthorizations().add(authorization);
+ }
+
+ private Subject newTokenSubject() {
+ return new Subject.Builder(securityManager)
+ .principals(SecurityUtils.asPrincipals(SecurityUtils.asAccessTokenPrincipal(token.getId())))
+ .buildSubject();
+ }
+
+ @Test
+ void projectEnumerationLoadsOwnerOnceForOneHundredGrantsAndRefreshesNextOperation() {
+ assertEquals(100, SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject()).size());
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ assertNull(AuthorizationInfoCache.get());
+
+ owner.getProjectAuthorizations().clear();
+ assertTrue(SecurityUtils.getAuthorizedProjects(newTokenSubject(), cache, new AccessProject()).isEmpty());
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+
+ @Test
+ void realmTokenAuthorizationAlsoLoadsOwnerOnceAndRefreshesForANewSubject() {
+ var permission = new ProjectPermission(projects.get(0), new AccessProject());
+ assertTrue(tokenSubject.isPermitted(permission));
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ assertNull(AuthorizationInfoCache.get());
+
+ owner.getProjectAuthorizations().clear();
+ assertFalse(newTokenSubject().isPermitted(permission));
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+
+ @Test
+ void roleLookupReusesOwnerInfoAcrossRejectedGrantsAndClosesOnEarlyReturn() {
+ for (int i = 1; i < projects.size(); i++)
+ projects.get(i).setParent(projects.get(i - 1));
+ var leaf = projects.get(projects.size() - 1);
+ owner.getProjectAuthorizations().clear();
+ grantOwner(leaf);
+ assertTrue(SecurityUtils.isAssignedRole(tokenSubject, leaf, role));
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ assertNull(AuthorizationInfoCache.get());
+
+ owner.getProjectAuthorizations().clear();
+ assertFalse(SecurityUtils.isAssignedRole(newTokenSubject(), leaf, role));
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+
+ @Test
+ void reportLookupSharesOwnerInfoBetweenAdministratorCheckAndGrantChecks() {
+ Map<String, Collection<String>> reports = Map.of("build", List.of("coverage"));
+ var accessible = SecurityUtils.getAccessibleReportNames(projects.get(0), Object.class, reports);
+ assertEquals(Set.of("coverage"), accessible.get("build"));
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ assertNull(AuthorizationInfoCache.get());
+
+ owner.getProjectAuthorizations().clear();
+ ThreadContext.bind(newTokenSubject());
+ assertTrue(SecurityUtils.getAccessibleReportNames(projects.get(0), Object.class, reports).isEmpty());
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void mixedGrantsPreserveProjectAndPrivilegeBoundaries(boolean deniedGrantFirst) {
+ var allowed = projects.get(0);
+ var denied = projects.get(1);
+ var child = projects.get(2);
+ child.setParent(allowed);
+ child.setPath(allowed.getPath() + "/" + child.getName());
+ cache.put(child.getId(), child.getFacade());
+ owner.getProjectAuthorizations().clear();
+ grantOwner(allowed);
+ var reader = new Role();
+ reader.setId(2L);
+ reader.setName("reader");
+ var job = new JobPrivilege();
+ job.setJobNames("build");
+ job.setAccessibleReports("coverage");
+ reader.getJobPrivileges().add(job);
+ var grants = new ArrayList<>(token.getAuthorizations());
+ var allowedGrant = grants.get(0);
+ allowedGrant.setRole(reader);
+ var deniedGrant = grants.get(1);
+ token.setAuthorizations(deniedGrantFirst ? List.of(deniedGrant, allowedGrant) : List.of(allowedGrant, deniedGrant));
+
+ assertEquals(Set.of(allowed, child),
+ SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject()));
+ assertTrue(SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new ManageProject()).isEmpty());
+ for (var project : List.of(allowed, child)) {
+ assertTrue(tokenSubject.isPermitted(new ProjectPermission(project, new AccessProject())));
+ assertFalse(SecurityUtils.canManageProject(tokenSubject, project));
+ assertTrue(SecurityUtils.isAssignedRole(tokenSubject, project, reader));
+ assertFalse(SecurityUtils.isAssignedRole(tokenSubject, project, role));
+ assertEquals(Map.of("build", Set.of("coverage")), SecurityUtils.getAccessibleReportNames(project,
+ Object.class, Map.of("build", List.of("coverage", "private"), "deploy", List.of("coverage"))));
+ }
+ for (var project : List.of(denied, projects.get(3))) {
+ assertFalse(tokenSubject.isPermitted(new ProjectPermission(project, new AccessProject())));
+ assertFalse(SecurityUtils.isAssignedRole(tokenSubject, project, role));
+ assertTrue(SecurityUtils.getAccessibleReportNames(project, Object.class,
+ Map.of("build", List.of("coverage"))).isEmpty());
+ }
+ }
+
+ @Test
+ void nestedOperationsKeepUsersTokensAndAnonymousPermissionsSeparate() {
+ var grants = new ArrayList<>(token.getAuthorizations());
+ token.setAuthorizations(List.of(grants.get(0)));
+ var otherToken = new AccessToken();
+ otherToken.setId(2L);
+ otherToken.setOwner(owner);
+ grants.get(1).setToken(otherToken);
+ otherToken.setAuthorizations(List.of(grants.get(1)));
+ when(tokens.get(otherToken.getId())).thenReturn(otherToken);
+ var otherSubject = new Subject.Builder(securityManager).principals(otherToken.getPrincipals()).buildSubject();
+ var root = new User();
+ root.setId(User.ROOT_ID);
+ root.setName("root");
+ assertEquals(token.getId(), root.getId());
+ when(users.get(root.getId())).thenReturn(root);
+ var rootSubject = new Subject.Builder(securityManager).principals(root.getPrincipals()).buildSubject();
+ var anonymous = new Subject.Builder(securityManager).principals(SecurityUtils.PRINCIPALS_ANONYMOUS).buildSubject();
+ try (var ignored = AuthorizationInfoCache.open()) {
+ assertTrue(rootSubject.isPermitted(new SystemAdministration()));
+ assertFalse(tokenSubject.isPermitted(new SystemAdministration()));
+ assertTrue(tokenSubject.isPermitted(new ProjectPermission(projects.get(0), new AccessProject())));
+ assertFalse(tokenSubject.isPermitted(new ProjectPermission(projects.get(1), new AccessProject())));
+ assertEquals(Set.of(projects.get(0)), SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject()));
+ assertEquals(Set.of(projects.get(1)), SecurityUtils.getAuthorizedProjects(otherSubject, cache, new AccessProject()));
+ assertFalse(otherSubject.isPermitted(new ProjectPermission(projects.get(0), new AccessProject())));
+ assertTrue(otherSubject.isPermitted(new ProjectPermission(projects.get(1), new AccessProject())));
+ assertFalse(anonymous.isPermitted(new SystemAdministration()));
+ assertTrue(SecurityUtils.getAuthorizedProjects(anonymous, cache, new ManageProject()).isEmpty());
+ assertSame(tokenSubject, ThreadContext.getSubject());
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ }
+ }
+
+ @Test
+ void ownerDisablementAndSubscriptionExpiryAreRespectedByNewSubjects() {
+ var permission = new ProjectPermission(projects.get(0), new AccessProject());
+ assertTrue(tokenSubject.isPermitted(permission));
+ owner.setDisabled(true);
+ assertFalse(newTokenSubject().isPermitted(permission));
+ assertTrue(SecurityUtils.getAuthorizedProjects(newTokenSubject(), cache, new AccessProject()).isEmpty());
+ owner.setDisabled(false);
+ assertTrue(newTokenSubject().isPermitted(permission));
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertFalse(newTokenSubject().isPermitted(permission));
+ assertTrue(SecurityUtils.getAuthorizedProjects(newTokenSubject(), cache, new AccessProject()).isEmpty());
+ }
+
+ @Test
+ void newWicketRequestDoesNotReuseRevokedOwnerPermissions() {
+ try (var requestCycles = mockStatic(RequestCycle.class)) {
+ var firstRequest = requestCycle();
+ requestCycles.when(RequestCycle::get).thenReturn(firstRequest);
+ var permission = new ProjectPermission(projects.get(0), new AccessProject());
+ assertTrue(tokenSubject.isPermitted(permission));
+ assertEquals(100, SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject()).size());
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ owner.getProjectAuthorizations().clear();
+ var nextRequest = requestCycle();
+ requestCycles.when(RequestCycle::get).thenReturn(nextRequest);
+ var newSubject = newTokenSubject();
+ assertFalse(newSubject.isPermitted(permission));
+ assertTrue(SecurityUtils.getAuthorizedProjects(newSubject, cache, new AccessProject()).isEmpty());
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+ }
+
+ private RequestCycle requestCycle() {
+ var requestCycle = mock(RequestCycle.class);
+ var metadata = new HashMap<MetaDataKey<?>, Object>();
+ when(requestCycle.getMetaData(any())).thenAnswer(it -> metadata.get(it.getArgument(0)));
+ doAnswer(it -> {
+ metadata.put(it.getArgument(0), it.getArgument(1));
+ return null;
+ }).when(requestCycle).setMetaData(any(), any());
+ return requestCycle;
+ }
+
+ @Test
+ void failureDuringTokenAuthorizationDoesNotLeakTheScope() {
+ var failure = new IllegalStateException("authorization lookup failed");
+ when(issueAuthorizations.getAuthorizedIssueIds(owner)).thenThrow(failure);
+ assertSame(failure, assertThrows(IllegalStateException.class,
+ () -> SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject())));
+ assertNull(AuthorizationInfoCache.get());
+
+ doReturn(Set.of()).when(issueAuthorizations).getAuthorizedIssueIds(owner);
+ assertEquals(100, SecurityUtils.getAuthorizedProjects(tokenSubject, cache, new AccessProject()).size());
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+
+ @Test
+ void nestedFailureKeepsOuterScopeAndSeparatesPrincipals() {
+ var otherUser = new User();
+ otherUser.setId(101L);
+ otherUser.setName("other");
+ when(users.get(otherUser.getId())).thenReturn(otherUser);
+ AuthorizationInfo ownerInfo;
+ try (var outer = AuthorizationInfoCache.open()) {
+ ownerInfo = authorizing.doGetAuthorizationInfo(owner.getPrincipals());
+ assertThrows(IllegalStateException.class, () -> {
+ try (var inner = AuthorizationInfoCache.open()) {
+ assertSame(ownerInfo, authorizing.doGetAuthorizationInfo(owner.getPrincipals()));
+ assertNotSame(ownerInfo, authorizing.doGetAuthorizationInfo(otherUser.getPrincipals()));
+ throw new IllegalStateException("nested failure");
+ }
+ });
+ assertSame(ownerInfo, authorizing.doGetAuthorizationInfo(owner.getPrincipals()));
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ verify(issueAuthorizations).getAuthorizedIssueIds(otherUser);
+ }
+ assertNull(AuthorizationInfoCache.get());
+ assertNotSame(ownerInfo, authorizing.doGetAuthorizationInfo(owner.getPrincipals()));
+ verify(issueAuthorizations, times(2)).getAuthorizedIssueIds(owner);
+ }
+
+ @Test
+ void scopeIsNotSharedWithOtherThreads() {
+ try (var outer = AuthorizationInfoCache.open()) {
+ var outerCache = AuthorizationInfoCache.get();
+ CompletableFuture.runAsync(() -> {
+ assertNull(AuthorizationInfoCache.get());
+ try (var inner = AuthorizationInfoCache.open()) {
+ assertNotSame(outerCache, AuthorizationInfoCache.get());
+ }
+ assertNull(AuthorizationInfoCache.get());
+ }).join();
+ assertSame(outerCache, AuthorizationInfoCache.get());
+ }
+ }
+
+ @Test
+ void wicketRequestCacheStillOutlivesIndividualOperations() {
+ try (var requestCycles = mockStatic(RequestCycle.class)) {
+ var requestCycle = mock(RequestCycle.class);
+ var requestCache = new HashMap<String, AuthorizationInfo>();
+ requestCycles.when(RequestCycle::get).thenReturn(requestCycle);
+ when(requestCycle.getMetaData(any())).thenAnswer(it -> requestCache);
+ AuthorizationInfo info;
+ try (var first = AuthorizationInfoCache.open()) {
+ info = authorizing.doGetAuthorizationInfo(owner.getPrincipals());
+ }
+ try (var second = AuthorizationInfoCache.open()) {
+ assertSame(info, authorizing.doGetAuthorizationInfo(owner.getPrincipals()));
+ }
+ verify(issueAuthorizations).getAuthorizedIssueIds(owner);
+ }
+ }
+
+}
diff --git a/server-core/src/test/java/io/onedev/server/security/ProjectDefaultsAuthorizationTest.java b/server-core/src/test/java/io/onedev/server/security/ProjectDefaultsAuthorizationTest.java
new file mode 100644
index 0000000000..f2bfc46521
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/security/ProjectDefaultsAuthorizationTest.java
@@ -0,0 +1,167 @@
+package io.onedev.server.security;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import org.apache.shiro.subject.Subject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.model.*;
+import io.onedev.server.persistence.SessionService;
+import io.onedev.server.security.permission.AccessProject;
+import io.onedev.server.security.permission.ProjectPermission;
+import io.onedev.server.service.*;
+import io.onedev.server.util.facade.ProjectCache;
+
+public class ProjectDefaultsAuthorizationTest {
+
+ private MockedStatic<OneDev> oneDev;
+ private SubscriptionService subscription;
+ private Project defaults;
+ private Project root;
+ private Project child;
+ private Project otherRoot;
+ private User user;
+ private Role role;
+ private Subject subject;
+ private ProjectCache cache;
+ private BaseAuthorizationService baseAuthorizations;
+ private DefaultAuthorizingService authorizing;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ oneDev = mockStatic(OneDev.class);
+ subscription = mock(SubscriptionService.class);
+ oneDev.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(subscription);
+ when(subscription.isSubscriptionActive()).thenReturn(true);
+ defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ root = project(1L, "root");
+ child = project(2L, "root/child");
+ child.setParent(root);
+ otherRoot = project(3L, "other");
+ var projects = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ cache = new ProjectCache(new HashMap<>());
+ for (var project : List.of(root, child, otherRoot)) {
+ cache.put(project.getId(), project.getFacade());
+ when(projects.load(project.getId())).thenReturn(project);
+ }
+ baseAuthorizations = mock(BaseAuthorizationService.class);
+ oneDev.when(() -> OneDev.getInstance(BaseAuthorizationService.class)).thenReturn(baseAuthorizations);
+ user = new User();
+ user.setId(100L);
+ user.setName("tester");
+ var users = mock(UserService.class);
+ oneDev.when(() -> OneDev.getInstance(UserService.class)).thenReturn(users);
+ when(users.get(user.getId())).thenReturn(user);
+ role = new Role();
+ role.setId(1L);
+ role.setName("reader");
+ subject = mock(Subject.class);
+ when(subject.getPrincipal()).thenReturn(SecurityUtils.asUserPrincipal(user.getId()));
+ var sessions = mock(SessionService.class);
+ when(sessions.call(any())).thenAnswer(it -> ((Callable<?>) it.getArgument(0)).call());
+ authorizing = new DefaultAuthorizingService();
+ inject("sessionService", sessions);
+ var settings = mock(SettingService.class);
+ when(settings.getIssueSetting()).thenReturn(new io.onedev.server.model.support.administration.GlobalIssueSetting());
+ oneDev.when(() -> OneDev.getInstance(SettingService.class)).thenReturn(settings);
+ inject("settingService", settings);
+ inject("issueAuthorizationService", mock(IssueAuthorizationService.class));
+ }
+
+ private void inject(String name, Object value) throws Exception {
+ var field = DefaultAuthorizingService.class.getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(authorizing, value);
+ }
+
+ private Project project(Long id, String path) {
+ var project = new Project();
+ project.setId(id);
+ project.setName(path);
+ project.setPath(path);
+ project.setLastActivityDate(new ProjectLastActivityDate());
+ return project;
+ }
+
+ @AfterEach
+ void tearDown() {
+ oneDev.close();
+ }
+
+ private void assertDefaultGrant(boolean expected) throws Exception {
+ var method = DefaultAuthorizingService.class.getDeclaredMethod("newAuthorizationInfo", String.class);
+ method.setAccessible(true);
+ var info = (org.apache.shiro.authz.AuthorizationInfo) method.invoke(authorizing, subject.getPrincipal());
+ for (var project : List.of(root, child, otherRoot)) {
+ assertEquals(expected, info.getObjectPermissions().stream()
+ .anyMatch(it -> it.implies(new ProjectPermission(project, new AccessProject()))));
+ assertEquals(expected, SecurityUtils.isAssignedRole(subject, project, role));
+ }
+ var visible = SecurityUtils.getAuthorizedProjects(subject, cache, new AccessProject());
+ assertEquals(expected ? 3 : 0, visible.size());
+ assertFalse(visible.contains(defaults));
+ }
+
+ @Test
+ void defaultUserAuthorizationControlsPermissionsAndProjectVisibility() throws Exception {
+ var authorization = new UserAuthorization();
+ authorization.setProject(defaults);
+ authorization.setUser(user);
+ authorization.setRole(role);
+ user.getProjectAuthorizations().add(authorization);
+ assertDefaultGrant(true);
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertDefaultGrant(false);
+ }
+
+ @Test
+ void defaultGroupAuthorizationControlsPermissionsAndProjectVisibility() throws Exception {
+ var group = new Group();
+ group.setId(1L);
+ var authorization = new GroupAuthorization();
+ authorization.setProject(defaults);
+ authorization.setGroup(group);
+ authorization.setRole(role);
+ group.getAuthorizations().add(authorization);
+ var membership = new Membership();
+ membership.setGroup(group);
+ membership.setUser(user);
+ user.getMemberships().add(membership);
+ assertDefaultGrant(true);
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertDefaultGrant(false);
+ }
+
+ @Test
+ void defaultRolesControlPermissionsAndProjectVisibility() throws Exception {
+ var authorization = new BaseAuthorization();
+ authorization.setProject(defaults);
+ authorization.setRole(role);
+ defaults.getBaseAuthorizations().add(authorization);
+ role.getBaseAuthorizations().add(authorization);
+ when(baseAuthorizations.query()).thenReturn(List.of(authorization));
+ assertDefaultGrant(true);
+ when(subscription.isSubscriptionActive()).thenReturn(false);
+ assertDefaultGrant(false);
+ }
+
+ @Test
+ void ordinaryGrantsStayWithinTheirProjectTree() {
+ var grant = new ProjectPermission(root, new AccessProject());
+ assertTrue(grant.implies(new ProjectPermission(child, new AccessProject())));
+ assertFalse(grant.implies(new ProjectPermission(otherRoot, new AccessProject())));
+ assertFalse(grant.implies(new ProjectPermission(defaults, new AccessProject())));
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/service/impl/DeletionReferenceTest.java b/server-core/src/test/java/io/onedev/server/service/impl/DeletionReferenceTest.java
index 9088549341..2fd7736202 100644
--- a/server-core/src/test/java/io/onedev/server/service/impl/DeletionReferenceTest.java
+++ b/server-core/src/test/java/io/onedev/server/service/impl/DeletionReferenceTest.java
@@ -35,6 +35,7 @@ import org.mockito.MockedStatic;
import io.onedev.commons.utils.ClassUtils;
import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
import io.onedev.server.model.AbstractEntity;
import io.onedev.server.model.Issue;
import io.onedev.server.model.IssueComment;
@@ -116,6 +117,7 @@ class DeletionReferenceTest {
application = mockStatic(OneDev.class);
application.when(() -> OneDev.getInstance(jakarta.validation.Validator.class)).thenReturn(validatorFactory.getValidator());
application.when(() -> OneDev.getInstance(SettingService.class)).thenReturn(settings);
+ application.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(mock(SubscriptionService.class));
var projects = mock(io.onedev.server.service.ProjectService.class);
when(projects.load(any())).thenAnswer(it -> session.find(Project.class, (Long) it.getArgument(0)));
application.when(() -> OneDev.getInstance(io.onedev.server.service.ProjectService.class)).thenReturn(projects);
diff --git a/server-core/src/test/java/io/onedev/server/service/impl/ProjectDefaultsGitPackTest.java b/server-core/src/test/java/io/onedev/server/service/impl/ProjectDefaultsGitPackTest.java
new file mode 100644
index 0000000000..f9954400cf
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/service/impl/ProjectDefaultsGitPackTest.java
@@ -0,0 +1,86 @@
+package io.onedev.server.service.impl;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.nio.file.Path;
+import java.util.Set;
+
+import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import com.hazelcast.map.IMap;
+
+import io.onedev.server.cluster.ClusterService;
+import io.onedev.server.event.entity.EntityPersisted;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.ProjectLastActivityDate;
+import io.onedev.server.model.support.code.GitPackConfig;
+import io.onedev.server.persistence.SessionService;
+import io.onedev.server.persistence.TransactionService;
+
+public class ProjectDefaultsGitPackTest {
+
+ @TempDir
+ Path directory;
+
+ private void inject(DefaultProjectService service, String name, Object value) throws Exception {
+ var field = DefaultProjectService.class.getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(service, value);
+ }
+
+ private Project project(Long id) {
+ var project = new Project();
+ project.setId(id);
+ project.setName("project" + id);
+ project.setPath(project.getName());
+ project.setLastActivityDate(new ProjectLastActivityDate());
+ return project;
+ }
+
+ @Test
+ void savingDefaultsDoesNotRefreshRepositoryConfigs() throws Exception {
+ var service = new DefaultProjectService(Set.of());
+ var defaults = project(Project.DEFAULT_ID);
+ defaults.getGitPackConfig().setThreads("2");
+ var sessions = mock(SessionService.class);
+ var transactions = mock(TransactionService.class);
+ var cluster = mock(ClusterService.class);
+ var replicas = mock(IMap.class);
+ inject(service, "sessionService", sessions);
+ inject(service, "transactionService", transactions);
+ inject(service, "clusterService", cluster);
+ inject(service, "replicas", replicas);
+ service.on(new EntityPersisted(defaults, false));
+ verifyNoInteractions(sessions, transactions, cluster, replicas);
+ }
+
+ @Test
+ void effectiveValuesAreWrittenAndClearedInRepositoryConfig() throws Exception {
+ var service = spy(new DefaultProjectService(Set.of()));
+ try (var repository = FileRepositoryBuilder.create(directory.resolve("repo.git").toFile())) {
+ repository.create(true);
+ doReturn(repository).when(service).getRepository(1L);
+ var config = new GitPackConfig();
+ config.setThreads("3");
+ config.setWindowMemory("128m");
+ config.setPackSizeLimit("1g");
+ config.setWindow("20");
+ service.checkGitConfig(1L, config);
+ var stored = repository.getConfig();
+ stored.load();
+ assertEquals("3", stored.getString("pack", null, "threads"));
+ assertEquals("128m", stored.getString("pack", null, "windowMemory"));
+ assertEquals("1g", stored.getString("pack", null, "packSizeLimit"));
+ assertEquals("20", stored.getString("pack", null, "window"));
+ service.checkGitConfig(1L, new GitPackConfig());
+ stored.load();
+ assertNull(stored.getString("pack", null, "threads"));
+ assertNull(stored.getString("pack", null, "windowMemory"));
+ assertNull(stored.getString("pack", null, "packSizeLimit"));
+ assertNull(stored.getString("pack", null, "window"));
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/service/impl/ProjectDefaultsParentTest.java b/server-core/src/test/java/io/onedev/server/service/impl/ProjectDefaultsParentTest.java
new file mode 100644
index 0000000000..0ecdb1be6e
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/service/impl/ProjectDefaultsParentTest.java
@@ -0,0 +1,85 @@
+package io.onedev.server.service.impl;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.Set;
+
+import org.apache.shiro.authz.Permission;
+import org.apache.shiro.subject.Subject;
+import org.junit.jupiter.api.Test;
+
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.model.Project;
+import io.onedev.server.persistence.dao.Dao;
+
+class ProjectDefaultsParentTest {
+
+ private Project project(Long id, String name) {
+ var project = new Project();
+ project.setId(id);
+ project.setName(name);
+ project.setPath(name);
+ return project;
+ }
+
+ @Test
+ void setupRejectsDefaultsAsTargetOrAncestorBeforeCheckingPermissions() {
+ var service = spy(new DefaultProjectService(Set.of()));
+ var defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ doReturn(defaults).when(service).find(any());
+ var subject = mock(Subject.class);
+ for (var path : new String[] {"~default", "~default/child", "~default/parent/child"})
+ assertThrows(ExplicitException.class, () -> service.setup(subject, path));
+ verifyNoInteractions(subject);
+ assertEquals(Project.DEFAULT_NAME, defaults.getPath());
+ }
+
+ @Test
+ void setupStillAllowsChildrenOfOrdinaryProjects() {
+ var service = spy(new DefaultProjectService(Set.of()));
+ var parent = project(1L, "parent");
+ doReturn(parent).doReturn(null).when(service).find(any());
+ var subject = mock(Subject.class);
+ when(subject.isPermitted(any(Permission.class))).thenReturn(true);
+ var child = service.setup(subject, "parent/child");
+ assertTrue(child.isNew());
+ assertSame(parent, child.getParent());
+ assertEquals("parent/child", child.getPath());
+ }
+
+ @Test
+ void createRejectsDefaultsAnywhereInTheParentChainBeforePersisting() {
+ var service = new DefaultProjectService(Set.of());
+ service.dao = mock(Dao.class);
+ var defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ var parent = project(null, "parent");
+ parent.setParent(defaults);
+ for (var ancestor : new Project[] {defaults, parent}) {
+ var child = project(null, "child");
+ child.setParent(ancestor);
+ assertThrows(ExplicitException.class, () -> service.create(null, child));
+ }
+ verifyNoInteractions(service.dao);
+ }
+
+ @Test
+ void updateRejectsMovingAnOrdinaryProjectUnderDefaults() {
+ var service = new DefaultProjectService(Set.of());
+ service.dao = mock(Dao.class);
+ var child = project(1L, "child");
+ child.setParent(project(Project.DEFAULT_ID, Project.DEFAULT_NAME));
+ assertThrows(ExplicitException.class, () -> service.update(child));
+ verifyNoInteractions(service.dao);
+ assertEquals("child", child.getPath());
+ }
+
+ @Test
+ void updatingDefaultsSettingsIsStillAllowed() {
+ var service = new DefaultProjectService(Set.of());
+ service.dao = mock(Dao.class);
+ var defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ service.update(defaults);
+ verify(service.dao).persist(defaults);
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/validation/HibernateValidationContainerConstraintTest.java b/server-core/src/test/java/io/onedev/server/validation/HibernateValidationContainerConstraintTest.java
new file mode 100644
index 0000000000..c7977a727f
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/validation/HibernateValidationContainerConstraintTest.java
@@ -0,0 +1,117 @@
+package io.onedev.server.validation;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.groups.Default;
+
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.annotation.ClassValidating;
+import io.onedev.server.annotation.DependsOn;
+
+public class HibernateValidationContainerConstraintTest extends HibernateValidationTestSupport {
+
+ @Test
+ public void elementConstraintsRunBeforeClassValidationInAllGroups() {
+ for (Class<?> group: new Class<?>[] {Default.class, Checks.class}) {
+ var bean = new Names();
+ assertPaths(validator.validate(bean, group), "names[0].<list element>");
+ assertEquals(0, bean.calls);
+ assertPaths(validator.validateProperty(bean, "names", group), "names[0].<list element>");
+ assertPaths(validator.validateValue(Names.class, "names", bean.names, group), "names[0].<list element>");
+ bean.names = List.of("valid");
+ assertPaths(validator.validate(bean, group));
+ assertEquals(1, bean.calls);
+ }
+ }
+
+ @Test
+ public void nestedFieldContainerElementsAreValidated() {
+ assertPaths(validator.validate(new NestedField()), "children[key].<map value>[0].<list element>");
+ }
+
+ @Test
+ public void elementConstraintsRespectGetterOverrides() {
+ assertPaths(validator.validate(new Parent()), "names[0].<list element>");
+ assertPaths(validator.validate(new Inherited()), "names[0].<list element>");
+ assertPaths(validator.validate(new Redeclared()), "names[0].<list element>");
+ assertPaths(validator.validate(new Removed()));
+ }
+
+ @Test
+ public void elementConstraintsRespectPropertyVisibility() {
+ var bean = new Dependent();
+ assertPaths(validator.validate(bean));
+ bean.enabled = true;
+ assertPaths(validator.validate(bean), "names[0].<list element>");
+ }
+
+ public interface Checks {
+ }
+
+ @ClassValidating(groups = {Default.class, Checks.class})
+ public static class Names implements Validatable {
+ List<String> names = Collections.singletonList(null);
+ int calls;
+
+ public List<@NotNull(groups = {Default.class, Checks.class}) String> getNames() {
+ return names;
+ }
+
+ @Override
+ public boolean isValid(ConstraintValidatorContext context) {
+ calls++;
+ return true;
+ }
+ }
+
+ public static class NestedField {
+ private final Map<String, List<@NotNull String>> children = Map.of("key", Collections.singletonList(null));
+
+ public Map<String, List<String>> getChildren() {
+ return children;
+ }
+ }
+
+ public static class Parent {
+ public List<@NotNull String> getNames() {
+ return Collections.singletonList(null);
+ }
+ }
+
+ public static class Inherited extends Parent {
+ }
+
+ public static class Redeclared extends Parent {
+ @Override
+ public List<@NotNull String> getNames() {
+ return super.getNames();
+ }
+ }
+
+ public static class Removed extends Parent {
+ @Override
+ public List<String> getNames() {
+ return super.getNames();
+ }
+ }
+
+ public static class Dependent {
+ boolean enabled;
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ @DependsOn(property = "enabled")
+ public List<@NotNull String> getNames() {
+ return Collections.singletonList(null);
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/web/component/user/accesstoken/AccessTokenDefaultsAuthorizationTest.java b/server-core/src/test/java/io/onedev/server/web/component/user/accesstoken/AccessTokenDefaultsAuthorizationTest.java
new file mode 100644
index 0000000000..61241c9d81
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/web/component/user/accesstoken/AccessTokenDefaultsAuthorizationTest.java
@@ -0,0 +1,181 @@
+package io.onedev.server.web.component.user.accesstoken;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.List;
+
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.NotFoundException;
+
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.shiro.subject.Subject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.exception.NoSubscriptionException;
+import io.onedev.server.exception.NotAcceptableException;
+import io.onedev.server.model.AccessToken;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.User;
+import io.onedev.server.rest.resource.AccessTokenAuthorizationResource;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.security.permission.ManageProject;
+import io.onedev.server.service.AccessTokenAuthorizationService;
+import io.onedev.server.service.AuditService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.util.HierarchicalContext;
+import io.onedev.server.util.ReflectionUtils;
+import io.onedev.server.web.util.UserAware;
+import io.onedev.server.web.util.WicketUtils;
+
+class AccessTokenDefaultsAuthorizationTest {
+
+ private MockedStatic<OneDev> oneDev;
+ private MockedStatic<SecurityUtils> security;
+ private MockedStatic<WicketUtils> wicket;
+ private ProjectService projects;
+ private Project defaults;
+ private Project ordinary;
+ private User owner;
+ private Subject ownerSubject;
+
+ @BeforeEach
+ void setUp() {
+ oneDev = mockStatic(OneDev.class);
+ security = mockStatic(SecurityUtils.class);
+ wicket = mockStatic(WicketUtils.class);
+ projects = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ defaults = new Project();
+ defaults.setId(Project.DEFAULT_ID);
+ defaults.setName(Project.DEFAULT_NAME);
+ defaults.setPath(Project.DEFAULT_NAME);
+ ordinary = new Project();
+ ordinary.setId(1L);
+ ordinary.setPath("ordinary");
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ when(projects.findByPath("ordinary")).thenReturn(ordinary);
+ owner = mock(User.class);
+ ownerSubject = mock(Subject.class);
+ when(owner.asSubject()).thenReturn(ownerSubject);
+ security.when(SecurityUtils::getAuthUser).thenReturn(owner);
+ security.when(() -> SecurityUtils.canManageProject(ownerSubject, defaults)).thenReturn(true);
+ security.when(() -> SecurityUtils.canManageProject(ownerSubject, ordinary)).thenReturn(true);
+ }
+
+ @AfterEach
+ void tearDown() {
+ wicket.close();
+ security.close();
+ oneDev.close();
+ }
+
+ @Test
+ void choiceAndDescriptionUseCurrentSubscriptionAndOwnerPermissions() {
+ var context = mock(HierarchicalContext.class);
+ var userAware = mock(UserAware.class);
+ when(context.findData(UserAware.class)).thenReturn(userAware);
+ when(userAware.getUser()).thenReturn(owner);
+ security.when(() -> SecurityUtils.getAuthorizedProjects(eq(ownerSubject), any(ManageProject.class)))
+ .thenReturn(List.of(ordinary));
+ HierarchicalContext.push(context);
+ try {
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ assertEquals(List.of(ordinary), choices());
+ assertEquals("", description());
+ verify(projects, never()).load(Project.DEFAULT_ID);
+ security.when(() -> SecurityUtils.isAdministrator(ownerSubject)).thenReturn(true);
+ assertEquals(List.of(defaults, ordinary), choices());
+ assertTrue(description().contains("~default"));
+ security.when(SecurityUtils::isAdministrator).thenReturn(false);
+ assertEquals(List.of(defaults, ordinary), choices());
+ assertTrue(description().contains("~default"));
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ assertEquals(List.of(ordinary), choices());
+ assertEquals("", description());
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertEquals(List.of(defaults, ordinary), choices());
+ assertTrue(description().contains("~default"));
+ } finally {
+ HierarchicalContext.pop();
+ }
+ }
+
+ private Object choices() {
+ return ReflectionUtils.invokeStaticMethod(AccessTokenAuthorizationBean.class, "getManageableProjects");
+ }
+
+ private String description() {
+ return (String) ReflectionUtils.invokeStaticMethod(AccessTokenAuthorizationBean.class, "getProjectDescription");
+ }
+
+ @Test
+ void resolvingDefaultChoiceUsesCurrentSubscriptionAndChecksOwnerPermission() {
+ var bean = new AccessTokenAuthorizationBean();
+ bean.setProjectPath(Project.DEFAULT_NAME);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ assertThrows(UnauthorizedException.class, () -> bean.resolveProject(owner));
+ verify(projects, never()).load(Project.DEFAULT_ID);
+ security.when(() -> SecurityUtils.isAdministrator(ownerSubject)).thenReturn(true);
+ assertSame(defaults, bean.resolveProject(owner));
+ verify(projects, never()).findByPath(Project.DEFAULT_NAME);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ assertThrows(NoSubscriptionException.class, () -> bean.resolveProject(owner));
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertSame(defaults, bean.resolveProject(owner));
+ security.when(() -> SecurityUtils.canManageProject(ownerSubject, defaults)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> bean.resolveProject(owner));
+
+ security.when(SecurityUtils::isAdministrator).thenReturn(false);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ bean.setProjectPath("ordinary");
+ assertSame(ordinary, bean.resolveProject(owner));
+ security.when(() -> SecurityUtils.canManageProject(ownerSubject, ordinary)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> bean.resolveProject(owner));
+ }
+
+ @Test
+ void restCreateAndUpdateEnforceTheSameDefaultScopeRules() {
+ var service = mock(AccessTokenAuthorizationService.class);
+ var resource = new AccessTokenAuthorizationResource(service, mock(AuditService.class));
+ var token = new AccessToken();
+ token.setOwner(owner);
+ var authorization = new AccessTokenAuthorization();
+ authorization.setId(5L);
+ authorization.setToken(token);
+ authorization.setProject(defaults);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertThrows(UnauthorizedException.class, () -> resource.createAuthorization(authorization));
+ assertThrows(UnauthorizedException.class, () -> resource.updateAuthorization(5L, authorization));
+ verifyNoInteractions(service);
+
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ assertThrows(BadRequestException.class, () -> resource.createAuthorization(authorization));
+ assertThrows(NotAcceptableException.class, () -> resource.updateAuthorization(5L, authorization));
+ verifyNoInteractions(service);
+ security.when(() -> SecurityUtils.isAdministrator(ownerSubject)).thenReturn(true);
+ assertEquals(5L, resource.createAuthorization(authorization));
+ assertEquals(200, resource.updateAuthorization(5L, authorization).getStatus());
+ verify(service, times(2)).createOrUpdate(authorization);
+ clearInvocations(service);
+
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ assertThrows(NoSubscriptionException.class, () -> resource.createAuthorization(authorization));
+ assertThrows(NoSubscriptionException.class, () -> resource.updateAuthorization(5L, authorization));
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ security.when(() -> SecurityUtils.canManageProject(ownerSubject, defaults)).thenReturn(false);
+ assertThrows(BadRequestException.class, () -> resource.createAuthorization(authorization));
+ assertThrows(NotAcceptableException.class, () -> resource.updateAuthorization(5L, authorization));
+ defaults.setId(-2L);
+ assertThrows(NotFoundException.class, () -> resource.createAuthorization(authorization));
+ assertThrows(NotFoundException.class, () -> resource.updateAuthorization(5L, authorization));
+ verifyNoInteractions(service);
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/web/editable/EditableUtilsTest.java b/server-core/src/test/java/io/onedev/server/web/editable/EditableUtilsTest.java
new file mode 100644
index 0000000000..8bc88743ad
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/web/editable/EditableUtilsTest.java
@@ -0,0 +1,50 @@
+package io.onedev.server.web.editable;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.model.Project;
+import io.onedev.server.model.support.ProjectAiSetting;
+import io.onedev.server.model.support.code.GitPackConfig;
+import io.onedev.server.web.util.WicketUtils;
+
+public class EditableUtilsTest {
+
+ @Test
+ public void inheritanceHelpMatchesProjectContext() throws Exception {
+ var property = ProjectAiSetting.class.getMethod("getExcludedReviewFiles");
+ var root = new Project();
+ root.setId(1L);
+ var child = new Project();
+ child.setId(2L);
+ child.setParent(root);
+ var defaults = new Project();
+ defaults.setId(Project.DEFAULT_ID);
+
+ try (var projects = mockStatic(Project.class); var wicket = mockStatic(WicketUtils.class)) {
+ var baseDescription = EditableUtils.getDescription(property);
+ assertFalse(baseDescription.contains("Leave empty"));
+
+ projects.when(Project::get).thenReturn(child);
+ assertTrue(EditableUtils.getDescription(property).endsWith("Leave empty to inherit from the parent project."));
+
+ projects.when(Project::get).thenReturn(root);
+ assertEquals(baseDescription, EditableUtils.getDescription(property));
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertTrue(EditableUtils.getDescription(property).contains(
+ "<a href='https://docs.onedev.io/administration-guide/project-defaults' target='_blank'>default setting</a>"));
+
+ projects.when(Project::get).thenReturn(child);
+ assertTrue(EditableUtils.getDescription(property).endsWith("Leave empty to inherit from the parent project."));
+ assertFalse(EditableUtils.getDescription(property).contains("project-defaults"));
+
+ projects.when(Project::get).thenReturn(defaults);
+ assertEquals(baseDescription, EditableUtils.getDescription(property));
+
+ projects.when(Project::get).thenReturn(root);
+ assertFalse(EditableUtils.getDescription(GitPackConfig.class.getMethod("getWindow")).contains("Leave empty"));
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/web/mapper/ProjectDefaultsMapperTest.java b/server-core/src/test/java/io/onedev/server/web/mapper/ProjectDefaultsMapperTest.java
new file mode 100644
index 0000000000..7349956df9
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/web/mapper/ProjectDefaultsMapperTest.java
@@ -0,0 +1,56 @@
+package io.onedev.server.web.mapper;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+
+import org.apache.wicket.core.request.handler.BookmarkablePageRequestHandler;
+import org.apache.wicket.core.request.handler.PageProvider;
+import org.apache.wicket.core.request.handler.RenderPageRequestHandler;
+import org.apache.wicket.mock.MockWebRequest;
+import org.apache.wicket.request.Url;
+import org.apache.wicket.util.tester.WicketTester;
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.model.Project;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.web.page.project.ProjectPage;
+import io.onedev.server.web.page.project.setting.wiki.WikiSettingPage;
+
+public class ProjectDefaultsMapperTest {
+
+ @Test
+ public void defaultsAndProjectEditorsUseSeparateRoutes() {
+ var tester = new WicketTester();
+ try (var oneDev = mockStatic(OneDev.class)) {
+ var projects = mock(ProjectService.class);
+ when(projects.getReservedNames()).thenReturn(List.of());
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ var defaults = new ProjectDefaultsMapper("wiki", WikiSettingPage.class);
+ var ordinary = new ProjectPageMapper("${project}/~settings/wiki", WikiSettingPage.class);
+ var defaultParams = ProjectPage.paramsOf(Project.DEFAULT_ID);
+ var defaultHandler = new BookmarkablePageRequestHandler(new PageProvider(WikiSettingPage.class, defaultParams));
+ assertEquals("~administration/project-defaults/wiki", defaults.mapHandler(defaultHandler).toString());
+ assertNull(ordinary.mapHandler(defaultHandler));
+
+ var projectParams = ProjectPage.paramsOf("parent/child");
+ var projectHandler = new BookmarkablePageRequestHandler(new PageProvider(WikiSettingPage.class, projectParams));
+ assertEquals("parent/child/~settings/wiki", ordinary.mapHandler(projectHandler).toString());
+ assertNull(defaults.mapHandler(projectHandler));
+
+ for (var query : new String[] {"", "?project=other"}) {
+ var request = new MockWebRequest(Url.parse("~administration/project-defaults/wiki" + query));
+ var mapped = (RenderPageRequestHandler) defaults.mapRequest(request);
+ assertEquals(WikiSettingPage.class, mapped.getPageClass());
+ assertEquals(Project.DEFAULT_NAME, mapped.getPageParameters().get(ProjectMapperUtils.PARAM_PROJECT).toString());
+ }
+ } finally {
+ tester.destroy();
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/web/page/project/setting/ProjectDefaultsTest.java b/server-core/src/test/java/io/onedev/server/web/page/project/setting/ProjectDefaultsTest.java
new file mode 100644
index 0000000000..179352c4a1
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/web/page/project/setting/ProjectDefaultsTest.java
@@ -0,0 +1,69 @@
+package io.onedev.server.web.page.project.setting;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.util.tester.WicketTester;
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.exception.NoSubscriptionException;
+import io.onedev.server.model.Project;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.web.mapper.ProjectMapperUtils;
+import io.onedev.server.web.page.project.setting.wiki.WikiSettingPage;
+import io.onedev.server.web.util.WicketUtils;
+
+public class ProjectDefaultsTest {
+
+ @Test
+ public void projectDefaultsAccessChecksApplyToNewPages() {
+ var project = new Project();
+ project.setId(Project.DEFAULT_ID);
+ var projects = mock(ProjectService.class);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(project);
+ var server = mock(OneDev.class);
+ when(server.isReady()).thenReturn(true);
+ try (var oneDev = mockStatic(OneDev.class); var security = mockStatic(SecurityUtils.class);
+ var wicket = mockStatic(WicketUtils.class)) {
+ oneDev.when(OneDev::getInstance).thenReturn(server);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ security.when(SecurityUtils::isAdministrator).thenReturn(true);
+ security.when(() -> SecurityUtils.canAccessProject(project)).thenReturn(true);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ var tester = new WicketTester();
+ try {
+ var params = new PageParameters().add(ProjectMapperUtils.PARAM_PROJECT, Project.DEFAULT_NAME);
+ var page = new WikiSettingPage(params);
+ assertSame(project, page.getProject());
+
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ assertSame(project, page.getProject());
+ assertThrows(NoSubscriptionException.class, () -> new WikiSettingPage(params));
+
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ security.when(SecurityUtils::isAdministrator).thenReturn(false);
+ assertSame(project, page.getProject());
+ assertThrows(UnauthorizedException.class, () -> new WikiSettingPage(params));
+ } finally {
+ tester.destroy();
+ }
+ }
+ }
+
+ @Test
+ public void systemProjectSuggestionsDoNotAccessGitStorage() {
+ var project = new Project();
+ project.setId(Project.DEFAULT_ID);
+ try (var oneDev = mockStatic(OneDev.class)) {
+ assertNull(project.getDefaultBranch());
+ assertTrue(project.getBranchRefs().isEmpty());
+ assertTrue(project.getTagRefs().isEmpty());
+ assertTrue(project.getJobNames().isEmpty());
+ oneDev.verifyNoInteractions();
+ }
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/web/util/WikiUtilsTest.java b/server-core/src/test/java/io/onedev/server/web/util/WikiUtilsTest.java
index 1f4639a58a..b02e5c1437 100644
--- a/server-core/src/test/java/io/onedev/server/web/util/WikiUtilsTest.java
+++ b/server-core/src/test/java/io/onedev/server/web/util/WikiUtilsTest.java
@@ -6,11 +6,14 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import org.jsoup.Jsoup;
import org.junit.jupiter.api.Test;
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
import io.onedev.server.model.Project;
import io.onedev.server.model.support.wiki.SpecifiedPath;
import io.onedev.server.model.support.wiki.WikiSetting;
@@ -126,24 +129,27 @@ public class WikiUtilsTest {
@Test
public void inheritsNearestConfiguredFolder() {
- Project parent = new Project();
- Project child = new Project();
- child.setParent(parent);
- assertEquals("wiki", child.getWikiFolder().getPath());
- parent.getWikiSetting().setFolder(specifiedPath("documentation"));
- assertEquals("documentation", child.getWikiFolder().getPath());
- child.getWikiSetting().setFolder(specifiedPath("docs/wiki"));
- assertEquals("docs/wiki", child.getWikiFolder().getPath());
- child.getWikiSetting().setFolder(null);
- assertEquals("documentation", child.getWikiFolder().getPath());
- child.getWikiSetting().setFolder(new RepositoryRoot());
- org.junit.jupiter.api.Assertions.assertNull(child.getWikiFolder().getPath());
- child.getWikiSetting().setFolder(null);
- parent.getWikiSetting().setFolder(new RepositoryRoot());
- org.junit.jupiter.api.Assertions.assertNull(child.getWikiFolder().getPath());
- parent.getWikiSetting().setFolder(null);
- assertTrue(parent.getWikiFolder() instanceof SpecifiedPath);
- assertEquals("wiki", child.getWikiFolder().getPath());
+ try (var services = mockStatic(OneDev.class)) {
+ services.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(mock(SubscriptionService.class));
+ Project parent = new Project();
+ Project child = new Project();
+ child.setParent(parent);
+ assertEquals("wiki", child.getWikiFolder().getPath());
+ parent.getWikiSetting().setFolder(specifiedPath("documentation"));
+ assertEquals("documentation", child.getWikiFolder().getPath());
+ child.getWikiSetting().setFolder(specifiedPath("docs/wiki"));
+ assertEquals("docs/wiki", child.getWikiFolder().getPath());
+ child.getWikiSetting().setFolder(null);
+ assertEquals("documentation", child.getWikiFolder().getPath());
+ child.getWikiSetting().setFolder(new RepositoryRoot());
+ org.junit.jupiter.api.Assertions.assertNull(child.getWikiFolder().getPath());
+ child.getWikiSetting().setFolder(null);
+ parent.getWikiSetting().setFolder(new RepositoryRoot());
+ org.junit.jupiter.api.Assertions.assertNull(child.getWikiFolder().getPath());
+ parent.getWikiSetting().setFolder(null);
+ assertTrue(parent.getWikiFolder() instanceof SpecifiedPath);
+ assertEquals("wiki", child.getWikiFolder().getPath());
+ }
}
@Test
diff --git a/server-core/src/test/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBeanTest.java b/server-core/src/test/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBeanTest.java
new file mode 100644
index 0000000000..4bf5074957
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/web/util/editbean/ProjectAuthorizationBeanTest.java
@@ -0,0 +1,57 @@
+package io.onedev.server.web.util.editbean;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.wicket.model.Model;
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.exception.NoSubscriptionException;
+import io.onedev.server.model.Project;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.util.ReflectionUtils;
+import io.onedev.server.util.facade.ProjectCache;
+import io.onedev.server.web.component.project.choice.ProjectChoiceProvider;
+import io.onedev.server.web.component.select2.Response;
+import io.onedev.server.web.util.WicketUtils;
+
+public class ProjectAuthorizationBeanTest {
+
+ @Test
+ public void defaultProjectChoiceAndResolutionUseCurrentSubscription() {
+ var project = new Project();
+ project.setId(Project.DEFAULT_ID);
+ project.setName(Project.DEFAULT_NAME);
+ project.setPath(Project.DEFAULT_NAME);
+ var service = mock(ProjectService.class);
+ when(service.cloneCache()).thenReturn(new ProjectCache(new HashMap<>()));
+ when(service.load(Project.DEFAULT_ID)).thenReturn(project);
+ try (var oneDev = mockStatic(OneDev.class); var wicket = mockStatic(WicketUtils.class)) {
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(service);
+ var bean = new ProjectAuthorizationBean();
+ bean.setProjectPath(Project.DEFAULT_NAME);
+ assertEquals(List.of(), ReflectionUtils.invokeStaticMethod(ProjectAuthorizationBean.class, "getProjectChoices"));
+ assertThrows(NoSubscriptionException.class, bean::resolveProject);
+ verify(service, never()).load(Project.DEFAULT_ID);
+
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertEquals(List.of(project), ReflectionUtils.invokeStaticMethod(ProjectAuthorizationBean.class, "getProjectChoices"));
+ assertSame(project, bean.resolveProject());
+ verify(service, never()).findByPath(Project.DEFAULT_NAME);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(false);
+ assertEquals(List.of(), ReflectionUtils.invokeStaticMethod(ProjectAuthorizationBean.class, "getProjectChoices"));
+ assertThrows(NoSubscriptionException.class, bean::resolveProject);
+ wicket.when(WicketUtils::isSubscriptionActive).thenReturn(true);
+ assertEquals(List.of(project), ReflectionUtils.invokeStaticMethod(ProjectAuthorizationBean.class, "getProjectChoices"));
+ assertSame(project, bean.resolveProject());
+
+ var response = new Response<Project>();
+ new ProjectChoiceProvider(Model.ofList(List.of(project))).query("~default", 0, response);
+ assertEquals(List.of(project), response.getResults());
+ }
+ }
+}
diff --git a/server-ee b/server-ee
index 7df8f8715b..4a4b197899 160000
--- a/server-ee
+++ b/server-ee
@@ -1 +1 @@
-Subproject commit 7df8f8715b37a7081e561c57371cc91e236db284
+Subproject commit 4a4b1978997ab34600574cda6a967fa901c28f8f