下面列出了hudson.model.BuildableItem#org.acegisecurity.context.SecurityContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if(1 + 1 == 2) {
SecurityContext oldCtx = SecurityContextHolder.getContext();
SecurityContextHolder.setContext(null); //
try {
super.doFilter(req, res, chain);
} finally {
SecurityContextHolder.setContext(oldCtx);
}
}
else {
super.doFilter(req, res, chain);
}
}
public Job<?, ?> getProject( String job, StaplerRequest req, StaplerResponse rsp )
throws HttpResponses.HttpResponseException
{
Job<?, ?> p;
SecurityContext orig = ACL.impersonate( ACL.SYSTEM );
try
{
p = Jenkins.getInstance().getItemByFullName( job, Job.class );
}
finally
{
SecurityContextHolder.setContext( orig );
}
if ( p == null )
{
throw org.kohsuke.stapler.HttpResponses.notFound();
}
return p;
}
@Override
public void test() {
SecurityContext sc = SecurityContextHolder.getContext();
if (sc.getAuthentication() != null)
System.out.println(sc.getAuthentication().getName()
+ " logged by test");
}
@Override
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if(!shouldApply(request)) {
chain.doFilter(req,rsp);
return;
}
Authentication token = verifyToken(request);
if(token==null) {
// no JWT token found, which is fine --- we just assume the request is authenticated in other means
// Some routes that require valid JWT token will check for the presence of JWT token during Stapler
// request routing, not here.
chain.doFilter(req,rsp);
return;
}
// run the rest of the request with the new identity
// create a new context and set it to holder to not clobber existing context
SecurityContext sc = new SecurityContextImpl();
sc.setAuthentication(token);
SecurityContext previous = SecurityContextHolder.getContext();
SecurityContextHolder.setContext(sc);
request.setAttribute(JWT_TOKEN_VALIDATED,true);
try {
chain.doFilter(req,rsp);
} finally {
if(previous != null){
SecurityContextHolder.setContext(previous);
}else {
SecurityContextHolder.clearContext();
}
}
}
@Setup(Level.Iteration)
public void setup() {
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(Objects.requireNonNull(User.getById("user33", true)).impersonate());
}
@Setup(Level.Iteration)
public void setup() {
SecurityContext holder = SecurityContextHolder.getContext();
holder.setAuthentication(Objects.requireNonNull(User.getById("user3", true)).impersonate());
}
protected String getLogin() {
SecurityContext sc = SecurityContextHolder.getContext();
if (sc.getAuthentication() == null)
return null;
return sc.getAuthentication().getName();
}
private SecurityContext getSecurityContext() {
return SecurityContextHolder.getContext();
}
protected String getLogin() {
SecurityContext context = getSecurityContext();
String login = context.getAuthentication().getName();
return login;
}
public @CheckForNull ScmServerEndpoint create(@JsonBody JSONObject request) {
List<ErrorMessage.Error> errors = Lists.newLinkedList();
// Validate name
final String name = (String) request.get(GithubServer.NAME);
if (StringUtils.isEmpty(name)) {
errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.NAME + " is required"));
} else {
GithubServer byName = findByName(name);
if (byName != null) {
errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.NAME + " already exists for server at '" + byName.getApiUrl() + "'"));
}
}
// Validate url
final String url = (String) request.get(GithubServer.API_URL);
if (StringUtils.isEmpty(url)) {
errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.API_URL + " is required"));
} else {
Endpoint byUrl = GitHubConfiguration.get().findEndpoint(url);
if (byUrl != null) {
errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + byUrl.getName() + "'"));
}
}
if (StringUtils.isNotEmpty(url)) {
// Validate that the URL represents a GitHub API endpoint
try {
HttpURLConnection connection = HttpRequest.get(url).connect();
if (connection.getHeaderField("X-GitHub-Request-Id") == null) {
errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_SERVER));
} else {
boolean isGithubCloud = false;
boolean isGithubEnterprise = false;
try {
InputStream inputStream;
int code = connection.getResponseCode();
if (200 <= code && code < 300) {
inputStream = HttpRequest.getInputStream(connection);
} else {
inputStream = HttpRequest.getErrorStream(connection);
}
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>(){};
Map<String, String> responseBody = GithubScm.getMappingObjectReader().forType(typeRef).readValue(inputStream);
isGithubCloud = code == 200 && responseBody.containsKey("current_user_url");
isGithubEnterprise = code == 401 && responseBody.containsKey("message");
} catch (IllegalArgumentException | IOException ioe) {
LOGGER.log(Level.INFO, "Could not parse response body from Github");
}
if (!isGithubCloud && !isGithubEnterprise) {
errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_APIURL));
}
}
} catch (Throwable e) {
errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.toString()));
LOGGER.log(Level.INFO, "Could not connect to Github", e);
}
}
if (errors.isEmpty()) {
SecurityContext old = null;
try {
// We need to escalate privilege to add user defined endpoint to
old = ACL.impersonate(ACL.SYSTEM);
GitHubConfiguration config = GitHubConfiguration.get();
String sanitizedUrl = discardQueryString(url);
Endpoint endpoint = new Endpoint(sanitizedUrl, name);
if (!config.addEndpoint(endpoint)) {
errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + endpoint.getName() + "'"));
} else {
return new GithubServer(endpoint, getLink());
}
}finally {
//reset back to original privilege level
if(old != null){
SecurityContextHolder.setContext(old);
}
}
}
ErrorMessage message = new ErrorMessage(400, "Failed to create GitHub server");
message.addAll(errors);
throw new ServiceException.BadRequestException(message);
}
public GogsResults triggerJobs(String jobName, String deliveryID) {
SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
GogsResults result = new GogsResults();
try {
BuildableItem project = GogsUtils.find(jobName, BuildableItem.class);
if (project != null) {
GogsTrigger gTrigger = null;
Cause cause = new GogsCause(deliveryID);
if (project instanceof ParameterizedJobMixIn.ParameterizedJob) {
ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) project;
for (Trigger trigger : pJob.getTriggers().values()) {
if (trigger instanceof GogsTrigger) {
gTrigger = (GogsTrigger) trigger;
break;
}
}
}
if (gTrigger != null) {
SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(project);
GogsPayload gogsPayload = new GogsPayload(this.payload);
if (item != null) {
item.scheduleBuild2(0, gogsPayload);
}
} else {
project.scheduleBuild(0, cause);
}
result.setMessage(String.format("Job '%s' is executed", jobName));
} else {
String msg = String.format("Job '%s' is not defined in Jenkins", jobName);
result.setStatus(404, msg);
LOGGER.warning(msg);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOGGER.severe(sw.toString());
} finally {
SecurityContextHolder.setContext(saveCtx);
}
return result;
}
/**
* Cancel previous builds for specified PR id.
*/
public int cancelQueuedBuildByPrNumber(final int id) {
int canceled = 0;
SecurityContext old = impersonate(ACL.SYSTEM);
try {
final Queue queue = getJenkinsInstance().getQueue();
final Queue.Item[] items = queue.getItems();
//todo replace with stream?
for (Queue.Item item : items) {
if (!(item.task instanceof Job)) {
LOGGER.debug("Item {} not instanceof job", item);
continue;
}
final Job<?, ?> jobTask = (Job<?, ?>) item.task;
if (!jobTask.getFullName().equals(job.getFullName())) {
LOGGER.debug("{} != {}", jobTask.getFullName(), job.getFullName());
continue;
}
final CauseAction action = item.getAction(CauseAction.class);
if (isNull(action)) {
LOGGER.debug("Cause action is null for {}", jobTask.getFullName());
continue;
}
Optional<Cause> cause = from(action.getCauses())
.filter(instanceOf(GitHubPRCause.class))
.firstMatch(new CauseHasPRNum(id));
if (cause.isPresent()) {
LOGGER.debug("Cancelling {}", item);
queue.cancel(item);
canceled++;
}
}
} finally {
SecurityContextHolder.setContext(old);
}
return canceled;
}
public void sessionDestroyed(HttpSessionEvent event) {
// Log the logout to the console.
log.info("Detected Logout Event");
// Get the Spring Application Context.
WebApplicationContext ctx = ApplicationContextFactory.getWebApplicationContext();
// We need to get the authentication context out of the
// event, as it doesn't necessarily exist through the
// standard Acegi tools.
String remoteUser = null;
Authentication auth = null;
SecurityContext acegiCtx = (SecurityContext) event.getSession().getAttribute("ACEGI_SECURITY_CONTEXT");
if( acegiCtx != null) {
auth = acegiCtx.getAuthentication();
if (auth != null) {
remoteUser = auth.getName();
}
}
if (remoteUser == null) {
remoteUser = "[UNKNOWN]";
}
// Actions to perform on logout.
lockManager = (LockManager) ctx.getBean("lockManager");
lockManager.releaseLocksForOwner(remoteUser);
if (auth != null) {
Object blob = auth.getDetails();
if (blob instanceof User) {
User user = (User) auth.getDetails();
Auditor auditor = (Auditor) ctx.getBean(Constants.BEAN_AUDITOR);
auditor.audit(user, User.class.getName(), user.getOid(), Auditor.ACTION_LOGOUT, "User " + remoteUser + " has logged out.");
}
SecurityContextHolder.clearContext();
// logout for duration
String sessionId = event.getSession().getId();
LogonDurationDAO logonDurationDAO = (LogonDurationDAO) ctx.getBean(Constants.BEAN_LOGON_DURATION_DAO);
logonDurationDAO.setLoggedOut(sessionId, new Date());
}
// Log the logout to the console.
log.info("Detected Logout Event for: " + remoteUser);
}
@Override
protected ModelAndView processFormSubmission(HttpServletRequest req,
HttpServletResponse resp, Object comm, BindException exc)
throws Exception {
ReportEmailCommand com = (ReportEmailCommand) comm;
ModelAndView mav = new ModelAndView();
if(com.getActionCmd().equals(ACTION_EMAIL)){
OperationalReport operationalReport = (OperationalReport) req.getSession().getAttribute("operationalReport");
// Get user's email address
// ...user
String remoteUser = null;
Authentication auth = null;
SecurityContext acegiCtx = (SecurityContext) req.getSession().getAttribute("ACEGI_SECURITY_CONTEXT");
if( acegiCtx != null) {
auth = acegiCtx.getAuthentication();
if (auth != null) {
remoteUser = auth.getName();
}
}
// ...email address
User user = (User) auth.getDetails();
String userEmailAddress = user.getEmail();
// Build attachment content
String dataAttachment = operationalReport.getRendering(com.getFormat());
// E-mail
Mailable email = new Mailable();
email.setRecipients(com.getRecipient());
email.setSender(userEmailAddress);
email.setSubject(com.getSubject());
email.setMessage(com.getMessage());
mailServer.send(email,
"report" + FileFactory.getFileExtension(com.getFormat()),
FileFactory.getMIMEType(com.getFormat()),
dataAttachment );
log.debug("email sent:");
log.debug(" from:" + userEmailAddress);
log.debug(" format=" + com.getFormat());
log.debug(" to=" + com.getRecipient());
log.debug(" subject=" + com.getSubject());
log.debug(" msg=" + com.getMessage());
mav.setViewName("reporting-preview");
} else {
log.error("Did not get send request: " + com.getActionCmd());
mav.setViewName("reporting-preview");
}
return mav;
}
private GHRepository setupMockGHRepository() throws Exception {
GHRepository ghRepository = PowerMockito.mock(GHRepository.class);
PowerMockito.whenNew(GHRepository.class).withNoArguments().thenReturn(ghRepository);
PowerMockito.when(ghRepository.getHooks()).thenReturn(new ArrayList<GHHook>());
PowerMockito.when(ghRepository.getHtmlUrl()).thenReturn(new URL("https://github.com/groupon/DotCi"));
GHHook hook = PowerMockito.mock(GHHook.class);
PowerMockito.when(ghRepository.createHook("web", new HashMap<String, String>() {{
put("url", "http://localhost/githook/");
}}, Arrays.asList(GHEvent.PUSH, GHEvent.PULL_REQUEST), true)).thenReturn(hook);
PowerMockito.when(ghRepository.isPrivate()).thenReturn(true);
PowerMockito.when(ghRepository.getDeployKeys()).thenReturn(new ArrayList<GHDeployKey>());
PowerMockito.when(ghRepository.addDeployKey("DotCi", null)).thenReturn(null);
PowerMockito.when(ghRepository.getName()).thenReturn("repo_name");
GHUser ghUser = PowerMockito.mock(GHUser.class);
PowerMockito.when(ghUser.getLogin()).thenReturn("theusername");
PowerMockito.when(ghRepository.getOwner()).thenReturn(ghUser);
String dotCiYaml = "environment:\n language: ruby\n\nbuild:\n before: echo \"get out of here denton\"\n run:\n unit: echo \"Unit test\"\n integration: echo \"Integration test\"\n after: echo it works right\n";
GHContent content = PowerMockito.mock(GHContent.class);
PowerMockito.when(content.getContent()).thenReturn(dotCiYaml);
PowerMockito.when(ghRepository.getFileContent(".ci.yml", "thisisasha")).thenReturn(content);
GHRef ghRef = PowerMockito.mock(GHRef.class);
GHRef.GHObject ghObject = PowerMockito.mock(GHRef.GHObject.class);
PowerMockito.when(ghObject.getSha()).thenReturn("thisisasha");
PowerMockito.when(ghRef.getObject()).thenReturn(ghObject);
PowerMockito.when(ghRepository.getRef("heads/master")).thenReturn(ghRef);
GHMyself myself = PowerMockito.mock(GHMyself.class);
PowerMockito.when(myself.getLogin()).thenReturn("someloginstuff");
PowerMockito.mockStatic(GitHub.class);
GitHub github = PowerMockito.mock(GitHub.class);
//PowerMockito.when(GitHub.connectUsingOAuth("https://localhost/api/v3", "thisismytoken")).thenReturn(github);
PowerMockito.when(github.getMyself()).thenReturn(myself);
PowerMockito.when(github.getRepository("groupon/DotCi")).thenReturn(ghRepository);
SecurityContext context = PowerMockito.mock(SecurityContext.class);
// PowerMockito.when(context.getAuthentication()).thenReturn(token);
SecurityContextHolder.setContext(context);
return ghRepository;
}