Search in sources :

Example 1 with Authentication

use of org.acegisecurity.Authentication in project hudson-2.x by hudson.

the class CLIRegisterer method discover.

private List<ExtensionComponent<CLICommand>> discover(final Hudson hudson) {
    LOGGER.fine("Listing up @CLIMethod");
    List<ExtensionComponent<CLICommand>> r = new ArrayList<ExtensionComponent<CLICommand>>();
    try {
        for (final Method m : Util.filter(Index.list(CLIMethod.class, hudson.getPluginManager().uberClassLoader), Method.class)) {
            try {
                // command name
                final String name = m.getAnnotation(CLIMethod.class).name();
                final ResourceBundleHolder res = loadMessageBundle(m);
                // make sure we have the resource, to fail early
                res.format("CLI." + name + ".shortDescription");
                r.add(new ExtensionComponent<CLICommand>(new CloneableCLICommand() {

                    @Override
                    public String getName() {
                        return name;
                    }

                    public String getShortDescription() {
                        // format by using the right locale
                        return res.format("CLI." + name + ".shortDescription");
                    }

                    @Override
                    public int main(List<String> args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) {
                        this.stdout = stdout;
                        this.stderr = stderr;
                        this.locale = locale;
                        this.channel = Channel.current();
                        registerOptionHandlers();
                        CmdLineParser parser = new CmdLineParser(null);
                        try {
                            SecurityContext sc = SecurityContextHolder.getContext();
                            Authentication old = sc.getAuthentication();
                            try {
                                //  build up the call sequence
                                Stack<Method> chains = new Stack<Method>();
                                Method method = m;
                                while (true) {
                                    chains.push(method);
                                    if (Modifier.isStatic(method.getModifiers()))
                                        // the chain is complete.
                                        break;
                                    // the method in question is an instance method, so we need to resolve the instance by using another resolver
                                    Class<?> type = method.getDeclaringClass();
                                    method = findResolver(type);
                                    if (method == null) {
                                        stderr.println("Unable to find the resolver method annotated with @CLIResolver for " + type);
                                        return 1;
                                    }
                                }
                                List<MethodBinder> binders = new ArrayList<MethodBinder>();
                                while (!chains.isEmpty()) binders.add(new MethodBinder(chains.pop(), parser));
                                // authentication
                                CliAuthenticator authenticator = Hudson.getInstance().getSecurityRealm().createCliAuthenticator(this);
                                new ClassParser().parse(authenticator, parser);
                                // fill up all the binders
                                parser.parseArgument(args);
                                Authentication auth = authenticator.authenticate();
                                if (auth == Hudson.ANONYMOUS)
                                    auth = loadStoredAuthentication();
                                // run the CLI with the right credential
                                sc.setAuthentication(auth);
                                hudson.checkPermission(Hudson.READ);
                                // resolve them
                                Object instance = null;
                                for (MethodBinder binder : binders) instance = binder.call(instance);
                                if (instance instanceof Integer)
                                    return (Integer) instance;
                                else
                                    return 0;
                            } catch (InvocationTargetException e) {
                                Throwable t = e.getTargetException();
                                if (t instanceof Exception)
                                    throw (Exception) t;
                                throw e;
                            } finally {
                                // restore
                                sc.setAuthentication(old);
                            }
                        } catch (CmdLineException e) {
                            stderr.println(e.getMessage());
                            printUsage(stderr, parser);
                            return 1;
                        } catch (Exception e) {
                            e.printStackTrace(stderr);
                            return 1;
                        }
                    }

                    protected int run() throws Exception {
                        throw new UnsupportedOperationException();
                    }
                }));
            } catch (ClassNotFoundException e) {
                LOGGER.log(SEVERE, "Failed to process @CLIMethod: " + m, e);
            }
        }
    } catch (IOException e) {
        LOGGER.log(SEVERE, "Failed to discvoer @CLIMethod", e);
    }
    return r;
}
Also used : Locale(java.util.Locale) ExtensionComponent(hudson.ExtensionComponent) CloneableCLICommand(hudson.cli.CloneableCLICommand) ArrayList(java.util.ArrayList) CliAuthenticator(hudson.security.CliAuthenticator) ArrayList(java.util.ArrayList) List(java.util.List) PrintStream(java.io.PrintStream) CmdLineParser(org.kohsuke.args4j.CmdLineParser) InputStream(java.io.InputStream) Method(java.lang.reflect.Method) IOException(java.io.IOException) ResourceBundleHolder(org.jvnet.localizer.ResourceBundleHolder) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CmdLineException(org.kohsuke.args4j.CmdLineException) Stack(java.util.Stack) CLICommand(hudson.cli.CLICommand) CloneableCLICommand(hudson.cli.CloneableCLICommand) Authentication(org.acegisecurity.Authentication) SecurityContext(org.acegisecurity.context.SecurityContext) CmdLineException(org.kohsuke.args4j.CmdLineException) ClassParser(org.kohsuke.args4j.ClassParser)

Example 2 with Authentication

use of org.acegisecurity.Authentication in project hudson-2.x by hudson.

the class DependencyRunner method run.

public void run() {
    Authentication saveAuth = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
        Set<AbstractProject> topLevelProjects = new HashSet<AbstractProject>();
        // Get all top-level projects
        LOGGER.fine("assembling top level projects");
        for (AbstractProject p : Hudson.getInstance().getAllItems(AbstractProject.class)) if (p.getUpstreamProjects().size() == 0) {
            LOGGER.fine("adding top level project " + p.getName());
            topLevelProjects.add(p);
        } else {
            LOGGER.fine("skipping project since not a top level project: " + p.getName());
        }
        populate(topLevelProjects);
        for (AbstractProject p : polledProjects) {
            LOGGER.fine("running project in correct dependency order: " + p.getName());
            runnable.run(p);
        }
    } finally {
        SecurityContextHolder.getContext().setAuthentication(saveAuth);
    }
}
Also used : Authentication(org.acegisecurity.Authentication) AbstractProject(hudson.model.AbstractProject) HashSet(java.util.HashSet)

Example 3 with Authentication

use of org.acegisecurity.Authentication in project blueocean-plugin by jenkinsci.

the class PipelineStepImpl method parseValue.

private Object parseValue(InputStepExecution execution, JSONArray parameters, StaplerRequest request) throws IOException, InterruptedException {
    Map<String, Object> mapResult = new HashMap<String, Object>();
    InputStep input = execution.getInput();
    for (Object o : parameters) {
        JSONObject p = (JSONObject) o;
        String name = (String) p.get(NAME_ELEMENT);
        if (name == null) {
            throw new ServiceException.BadRequestExpception("name is required parameter element");
        }
        ParameterDefinition d = null;
        for (ParameterDefinition def : input.getParameters()) {
            if (def.getName().equals(name))
                d = def;
        }
        if (d == null)
            throw new ServiceException.BadRequestExpception("No such parameter definition: " + name);
        ParameterValue v = d.createValue(request, p);
        if (v == null) {
            continue;
        }
        mapResult.put(name, convert(name, v));
    }
    // If a destination value is specified, push the submitter to it.
    String valueName = input.getSubmitterParameter();
    if (valueName != null && !valueName.isEmpty()) {
        Authentication a = Jenkins.getAuthentication();
        mapResult.put(valueName, a.getName());
    }
    switch(mapResult.size()) {
        case 0:
            // no value if there's no parameter
            return null;
        case 1:
            return mapResult.values().iterator().next();
        default:
            return mapResult;
    }
}
Also used : JSONObject(net.sf.json.JSONObject) ServiceException(io.jenkins.blueocean.commons.ServiceException) FileParameterValue(hudson.model.FileParameterValue) ParameterValue(hudson.model.ParameterValue) HashMap(java.util.HashMap) Authentication(org.acegisecurity.Authentication) InputStep(org.jenkinsci.plugins.workflow.support.steps.input.InputStep) BlueInputStep(io.jenkins.blueocean.rest.model.BlueInputStep) JSONObject(net.sf.json.JSONObject) ParameterDefinition(hudson.model.ParameterDefinition)

Example 4 with Authentication

use of org.acegisecurity.Authentication in project blueocean-plugin by jenkinsci.

the class PipelineStepImpl method canSubmit.

private boolean canSubmit(InputStep inputStep) {
    Authentication a = Jenkins.getAuthentication();
    String submitter = inputStep.getSubmitter();
    if (submitter == null || a.getName().equals(submitter)) {
        return true;
    }
    for (GrantedAuthority ga : a.getAuthorities()) {
        if (ga.getAuthority().equals(submitter)) {
            return true;
        }
    }
    return false;
}
Also used : Authentication(org.acegisecurity.Authentication) GrantedAuthority(org.acegisecurity.GrantedAuthority)

Example 5 with Authentication

use of org.acegisecurity.Authentication in project blueocean-plugin by jenkinsci.

the class BlueOceanCredentialsProvider method getCredentials.

@Nonnull
public <C extends Credentials> List<C> getCredentials(@Nonnull final Class<C> type, @Nullable ItemGroup itemGroup, @Nullable Authentication authentication, @Nonnull List<DomainRequirement> domainRequirements) {
    final List<C> result = new ArrayList<>();
    final FolderPropertyImpl prop = propertyOf(itemGroup);
    if (prop != null && prop.domain.test(domainRequirements)) {
        final User proxyUser = User.get(prop.getUser(), false, Collections.emptyMap());
        Authentication proxyAuth = proxyUser == null ? null : proxyUser.impersonate();
        if (proxyAuth != null) {
            ACL.impersonate(proxyAuth, new Runnable() {

                @Override
                public void run() {
                    for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                        for (Domain d : s.getDomains()) {
                            if (d.test(PROXY_REQUIREMENT)) {
                                for (Credentials c : filter(s.getCredentials(d), withId(prop.getId()))) {
                                    if (type.isInstance(c)) {
                                        result.add((C) c);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }
    return result;
}
Also used : User(hudson.model.User) Authentication(org.acegisecurity.Authentication) ArrayList(java.util.ArrayList) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) Domain(com.cloudbees.plugins.credentials.domains.Domain) Credentials(com.cloudbees.plugins.credentials.Credentials) IdCredentials(com.cloudbees.plugins.credentials.common.IdCredentials) Nonnull(javax.annotation.Nonnull)

Aggregations

Authentication (org.acegisecurity.Authentication)19 SecurityContext (org.acegisecurity.context.SecurityContext)6 User (hudson.model.User)4 ACL (hudson.security.ACL)3 Nonnull (javax.annotation.Nonnull)3 Item (hudson.model.Item)2 CliAuthenticator (hudson.security.CliAuthenticator)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpSession (javax.servlet.http.HttpSession)2 JSONObject (net.sf.json.JSONObject)2 CmdLineException (org.kohsuke.args4j.CmdLineException)2 Credentials (com.cloudbees.plugins.credentials.Credentials)1 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)1 IdCredentials (com.cloudbees.plugins.credentials.common.IdCredentials)1 Domain (com.cloudbees.plugins.credentials.domains.Domain)1 HashCode (com.google.common.hash.HashCode)1 AbortException (hudson.AbortException)1 ExtensionComponent (hudson.ExtensionComponent)1