summaryrefslogtreecommitdiffstats
path: root/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilter.java
blob: b1e3f8799d696e3adb1dada3f97b44b4edbbef69 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.filter;

import com.google.inject.Inject;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig;
import com.yahoo.jdisc.http.filter.security.cors.CorsRequestFilterBase;
import com.yahoo.log.LogLevel;
import com.yahoo.restapi.Path;
import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzPrincipal;
import com.yahoo.vespa.athenz.api.AthenzUser;
import com.yahoo.vespa.athenz.client.zms.ZmsClientException;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.TenantController;
import com.yahoo.vespa.hosted.controller.athenz.ApplicationAction;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactory;
import com.yahoo.vespa.hosted.controller.athenz.impl.ZmsClientFacade;
import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
import com.yahoo.vespa.hosted.controller.tenant.UserTenant;
import com.yahoo.yolean.chain.After;
import com.yahoo.yolean.chain.Provides;

import javax.ws.rs.ForbiddenException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.WebApplicationException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;

import static com.yahoo.jdisc.http.HttpRequest.Method.GET;
import static com.yahoo.jdisc.http.HttpRequest.Method.HEAD;
import static com.yahoo.jdisc.http.HttpRequest.Method.OPTIONS;
import static com.yahoo.jdisc.http.HttpRequest.Method.POST;
import static com.yahoo.jdisc.http.HttpRequest.Method.PUT;
import static com.yahoo.vespa.hosted.controller.athenz.HostedAthenzIdentities.SCREWDRIVER_DOMAIN;

/**
 * A security filter protects all controller apis.
 *
 * @author bjorncs
 */
@After("com.yahoo.vespa.hosted.controller.athenz.filter.UserAuthWithAthenzPrincipalFilter")
@Provides("ControllerAuthorizationFilter")
public class ControllerAuthorizationFilter extends CorsRequestFilterBase {

    private static final List<Method> WHITELISTED_METHODS = Arrays.asList(GET, OPTIONS, HEAD);

    private static final Logger log = Logger.getLogger(ControllerAuthorizationFilter.class.getName());

    private final ZmsClientFacade zmsClient;
    private final TenantController tenantController;

    @Inject
    public ControllerAuthorizationFilter(AthenzClientFactory clientFactory,
                                         Controller controller,
                                         CorsFilterConfig corsConfig) {
        super(corsConfig);
        this.zmsClient = new ZmsClientFacade(clientFactory.createZmsClient(), clientFactory.getControllerIdentity());
        this.tenantController = controller.tenants();
    }

    ControllerAuthorizationFilter(AthenzClientFactory clientFactory,
                                  TenantController tenantController,
                                  Set<String> allowedUrls) {
        super(allowedUrls);
        this.zmsClient = new ZmsClientFacade(clientFactory.createZmsClient(), clientFactory.getControllerIdentity());;
        this.tenantController = tenantController;
    }

    // NOTE: Be aware of the ordering of the path pattern matching. Semantics may change if the patterns are evaluated
    //       in different order.
    @Override
    public Optional<ErrorResponse> filterRequest(DiscFilterRequest request) {
        Method method = getMethod(request);
        if (isWhiteListedMethod(method)) return Optional.empty();

        try {
            Path path = new Path(request.getRequestURI());
            AthenzPrincipal principal = getPrincipalOrThrow(request);
            if (isWhiteListedOperation(path, method)) {
                // no authz check
            } else if (isHostedOperatorOperation(path, method)) {
                verifyIsHostedOperator(principal);
            } else if (isTenantAdminOperation(path, method)) {
                verifyIsTenantAdmin(principal, getTenantName(path));
            } else if (isTenantPipelineOperation(path, method)) {
                verifyIsTenantPipelineOperator(principal, getTenantName(path), getApplicationName(path));
            } else {
                throw new ForbiddenException("No access control is declared for path: '" + path.asString() + "'");
            }
            return Optional.empty();
        } catch (WebApplicationException e) {
            int statusCode = e.getResponse().getStatus();
            String errorMessage = e.getMessage();
            log.log(LogLevel.WARNING, String.format("Access denied (%d): %s", statusCode, errorMessage));
            return Optional.of(new ErrorResponse(statusCode, errorMessage));
        }
    }

    private static boolean isWhiteListedMethod(Method method) {
        return WHITELISTED_METHODS.contains(method);
    }

    private static boolean isWhiteListedOperation(Path path, Method method) {
        return path.matches("/application/v4/user") && method == PUT || // Create user tenant
               path.matches("/application/v4/tenant/{tenant}") && method == POST; // Create tenant
    }

    private static boolean isHostedOperatorOperation(Path path, Method method) {
        if (isWhiteListedOperation(path, method)) return false;
        return path.matches("/controller/v1/{*}") ||
               path.matches("/provision/v2/{*}") ||
               path.matches("/screwdriver/v1/trigger/tenant/{*}") ||
               path.matches("/os/v1/{*}") ||
               path.matches("/zone/v2/{*}") ||
               path.matches("/nodes/v2/{*}") ||
               path.matches("/orchestrator/v1/{*}");
    }

    private static boolean isTenantAdminOperation(Path path, Method method) {
        if (isHostedOperatorOperation(path, method)) return false;
        return path.matches("/application/v4/tenant/{tenant}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/deploying") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/job/{job}/{*}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/dev/{*}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/perf/{*}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{instance}/global-rotation/override");
    }

    private static boolean isTenantPipelineOperation(Path path, Method method) {
        if (isTenantAdminOperation(path, method)) return false;
        return path.matches("/application/v4/tenant/{tenant}/application/{application}/jobreport") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/submit") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/promote") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/prod/{*}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/test/{*}") ||
               path.matches("/application/v4/tenant/{tenant}/application/{application}/environment/staging/{*}");
    }

    private void verifyIsHostedOperator(AthenzPrincipal principal) {
        if (!isHostedOperator(principal.getIdentity())) {
            throw new ForbiddenException("Vespa operator role required");
        }
    }

    private boolean isHostedOperator(AthenzIdentity identity) {
        return zmsClient.hasHostedOperatorAccess(identity);
    }

    private void verifyIsTenantAdmin(AthenzPrincipal principal, TenantName name) {
        tenantController.tenant(name)
                .ifPresent(tenant -> {
                    if (!isTenantAdmin(principal.getIdentity(), tenant)) {
                        throw new ForbiddenException("Tenant admin or Vespa operator role required");
                    }
                });
    }

    private boolean isTenantAdmin(AthenzIdentity identity, Tenant tenant) {
        if (tenant instanceof AthenzTenant) {
            return zmsClient.hasTenantAdminAccess(identity, ((AthenzTenant) tenant).domain());
        } else if (tenant instanceof UserTenant) {
            if (!(identity instanceof AthenzUser)) {
                return false;
            }
            AthenzUser user = (AthenzUser) identity;
            return ((UserTenant) tenant).is(user.getName()) || isHostedOperator(identity);
        }
        throw new InternalServerErrorException("Unknown tenant type: " + tenant.getClass().getSimpleName());
    }

    private void verifyIsTenantPipelineOperator(AthenzPrincipal principal,
                                                TenantName name,
                                                ApplicationName application) {
        tenantController.tenant(name)
                .ifPresent(tenant -> verifyIsTenantPipelineOperator(principal.getIdentity(), tenant, application));
    }

    private void verifyIsTenantPipelineOperator(AthenzIdentity identity, Tenant tenant, ApplicationName application) {
        if (isHostedOperator(identity)) return;

        AthenzDomain principalDomain = identity.getDomain();
        if (!principalDomain.equals(SCREWDRIVER_DOMAIN)) {
            throw new ForbiddenException(String.format(
                    "'%s' is not a Screwdriver identity. Only Screwdriver is allowed to deploy to this environment.",
                    identity.getFullName()));
        }

        // NOTE: no fine-grained deploy authorization for non-Athenz tenants
        if (tenant instanceof AthenzTenant) {
            AthenzDomain tenantDomain = ((AthenzTenant) tenant).domain();
            if (!hasDeployerAccess(identity, tenantDomain, application)) {
                throw new ForbiddenException(String.format(
                        "'%1$s' does not have access to '%2$s'. " +
                                "Either the application has not been created at Vespa dashboard or " +
                                "'%1$s' is not added to the application's deployer role in Athenz domain '%3$s'.",
                        identity.getFullName(), application.value(), tenantDomain.getName()));
            }
        }
    }

    private boolean hasDeployerAccess(AthenzIdentity identity, AthenzDomain tenantDomain, ApplicationName application) {
        try {
            return zmsClient
                    .hasApplicationAccess(
                            identity,
                            ApplicationAction.deploy,
                            tenantDomain,
                            new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(application.value()));
        } catch (ZmsClientException e) {
            throw new InternalServerErrorException("Failed to authorize operation:  (" + e.getMessage() + ")", e);
        }
    }

    private static TenantName getTenantName(Path path) {
        if (!path.matches("/application/v4/tenant/{tenant}/{*}"))
            throw new InternalServerErrorException("Unable to handle path: " + path.asString());
        return TenantName.from(path.get("tenant"));
    }

    private static ApplicationName getApplicationName(Path path) {
        if (!path.matches("/application/v4/tenant/{tenant}/application/{application}/{*}"))
            throw new InternalServerErrorException("Unable to handle path: " + path.asString());
        return ApplicationName.from(path.get("application"));
    }

    private static Method getMethod(DiscFilterRequest request) {
        return Method.valueOf(request.getMethod().toUpperCase());
    }

    private static AthenzPrincipal getPrincipalOrThrow(DiscFilterRequest request) {
        return getPrincipal(request)
                .orElseThrow(() -> new NotAuthorizedException("User not authenticated"));
    }

    private static Optional<AthenzPrincipal> getPrincipal(DiscFilterRequest request) {
        return Optional.ofNullable(request.getUserPrincipal())
                .map(AthenzPrincipal.class::cast);
    }

}