com.netflix.spinnaker.fiat.model.Authorization Java Examples

The following examples show how to use com.netflix.spinnaker.fiat.model.Authorization. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Permissions.java    From fiat with Apache License 2.0 6 votes vote down vote up
private static Permissions fromMap(Map<Authorization, List<String>> authConfig) {
  final Map<Authorization, List<String>> perms = new EnumMap<>(Authorization.class);
  for (Authorization auth : Authorization.values()) {
    Optional.ofNullable(authConfig.get(auth))
        .map(
            groups ->
                groups.stream()
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(String::toLowerCase)
                    .collect(Collectors.toList()))
        .filter(g -> !g.isEmpty())
        .map(Collections::unmodifiableList)
        .ifPresent(roles -> perms.put(auth, roles));
  }
  return new Permissions(perms);
}
 
Example #2
Source File: ChaosMonkeyEventListener.java    From front50 with Apache License 2.0 6 votes vote down vote up
protected void applyNewPermissions(
    Application.Permission updatedPermission, boolean chaosMonkeyEnabled) {
  Permissions permissions = updatedPermission.getPermissions();

  Map<Authorization, List<String>> unpackedPermissions = permissions.unpack();
  unpackedPermissions.forEach(
      (key, value) -> {
        List<String> roles = new ArrayList<>(value);
        if (key == Authorization.READ || key == Authorization.WRITE) {
          if (chaosMonkeyEnabled && shouldAdd(updatedPermission, key)) {
            roles.add(properties.getUserRole());
          } else if (chaosMonkeyEnabled && shouldRemove(updatedPermission, key)) {
            roles.removeAll(Collections.singletonList(properties.getUserRole()));
          } else if (!chaosMonkeyEnabled) {
            roles.removeAll(Collections.singletonList(properties.getUserRole()));
          }
        }
        unpackedPermissions.put(key, roles);
      });
  Permissions newPermissions = Permissions.factory(unpackedPermissions);

  updatedPermission.setPermissions(newPermissions);
}
 
Example #3
Source File: Application.java    From front50 with Apache License 2.0 6 votes vote down vote up
@JsonSetter
public void setRequiredGroupMembership(List<String> requiredGroupMembership) {
  log.warn(
      "Required group membership settings detected in application {} "
          + "Please update to `permissions` format.",
      StructuredArguments.value("application", name));

  if (!permissions.isRestricted()) { // Do not overwrite permissions if it contains values
    final Permissions.Builder b = new Permissions.Builder();
    requiredGroupMembership.forEach(
        it -> {
          b.add(Authorization.READ, it.trim().toLowerCase());
          b.add(Authorization.WRITE, it.trim().toLowerCase());
        });
    permissions = b.build();
  }
}
 
Example #4
Source File: ApplicationResourcePermissionSource.java    From fiat with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public Permissions getPermissions(@Nonnull Application resource) {
  Permissions storedPermissions = resource.getPermissions();
  if (storedPermissions == null || !storedPermissions.isRestricted()) {
    return Permissions.EMPTY;
  }

  Map<Authorization, List<String>> authorizations =
      Arrays.stream(Authorization.values()).collect(toMap(identity(), storedPermissions::get));

  // CREATE permissions are not allowed on the resource level.
  authorizations.remove(Authorization.CREATE);

  return Permissions.Builder.factory(authorizations).build();
}
 
Example #5
Source File: PipelineInitiator.java    From echo with Apache License 2.0 6 votes vote down vote up
/**
 * The set of accounts that a user has WRITE access to.
 *
 * <p>Similar filtering can be found in `gate` (see AllowedAccountsSupport.java).
 *
 * @param user A service account name (or 'anonymous' if not specified)
 * @return the allowed accounts for {@param user} as determined by fiat
 */
private Set<String> getAllowedAccountsForUser(String user) {
  if (fiatPermissionEvaluator == null || !fiatStatus.isLegacyFallbackEnabled()) {
    return Collections.emptySet();
  }

  UserPermission.View userPermission = null;
  try {
    userPermission =
        AuthenticatedRequest.allowAnonymous(() -> fiatPermissionEvaluator.getPermission(user));
  } catch (Exception e) {
    log.error("Unable to fetch permission for {}", user, e);
  }

  if (userPermission == null) {
    return Collections.emptySet();
  }

  return userPermission.getAccounts().stream()
      .filter(v -> v.getAuthorizations().contains(Authorization.WRITE))
      .map(Account.View::getName)
      .collect(Collectors.toSet());
}
 
Example #6
Source File: AbstractConfigCommand.java    From halyard with Apache License 2.0 6 votes vote down vote up
protected static void updatePermissions(
    Permissions.Builder permissions,
    List<String> readPermissions,
    String addReadPermission,
    String removeReadPermission,
    List<String> writePermissions,
    String addWritePermission,
    String removeWritePermission) {
  List<String> resolvedReadPermissions =
      updateStringList(
          permissions.get(Authorization.READ),
          readPermissions,
          addReadPermission,
          removeReadPermission);
  List<String> resolvedWritePermissions =
      updateStringList(
          permissions.get(Authorization.WRITE),
          writePermissions,
          addWritePermission,
          removeWritePermission);

  permissions.clear();
  permissions.add(Authorization.READ, resolvedReadPermissions);
  permissions.add(Authorization.WRITE, resolvedWritePermissions);
}
 
Example #7
Source File: AbstractAddAccountCommand.java    From halyard with Apache License 2.0 6 votes vote down vote up
@Override
protected void executeThis() {
  String accountName = getAccountName();
  Account account = buildAccount(accountName);
  account.setRequiredGroupMembership(requiredGroupMembership);
  account.getPermissions().add(Authorization.READ, readPermissions);
  account.getPermissions().add(Authorization.WRITE, writePermissions);
  account.setEnvironment(isSet(environment) ? environment : account.getEnvironment());
  String providerName = getProviderName();

  String currentDeployment = getCurrentDeployment();
  new OperationHandler<Void>()
      .setFailureMesssage(
          "Failed to add account " + accountName + " for provider " + providerName + ".")
      .setSuccessMessage(
          "Successfully added account " + accountName + " for provider " + providerName + ".")
      .setOperation(Daemon.addAccount(currentDeployment, providerName, !noValidate, account))
      .get();
}
 
Example #8
Source File: AuthorizeController.java    From fiat with Apache License 2.0 5 votes vote down vote up
@RequestMapping(
    value = "/{userId:.+}/{resourceType:.+}/{resourceName:.+}/{authorization:.+}",
    method = RequestMethod.GET)
public void getUserAuthorization(
    @PathVariable String userId,
    @PathVariable String resourceType,
    @PathVariable String resourceName,
    @PathVariable String authorization,
    HttpServletResponse response)
    throws IOException {
  Authorization a = Authorization.valueOf(authorization.toUpperCase());
  ResourceType r = ResourceType.parse(resourceType);
  Set<Authorization> authorizations = new HashSet<>(0);

  try {
    if (r.equals(ResourceType.ACCOUNT)) {
      authorizations = getUserAccount(userId, resourceName).getAuthorizations();
    } else if (r.equals(ResourceType.APPLICATION)) {
      authorizations = getUserApplication(userId, resourceName).getAuthorizations();
    } else {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "Resource type " + resourceType + " does not contain authorizations");
      return;
    }
  } catch (NotFoundException nfe) {
    // Ignore. Will return 404 below.
  }

  if (authorizations.contains(a)) {
    response.setStatus(HttpServletResponse.SC_OK);
    return;
  }

  response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
 
Example #9
Source File: Application.java    From fiat with Apache License 2.0 5 votes vote down vote up
public View(Application application, Set<Role> userRoles, boolean isAdmin) {
  this.name = application.name;
  if (isAdmin) {
    this.authorizations = Authorization.ALL;
  } else {
    this.authorizations = application.permissions.getAuthorizations(userRoles);
  }
}
 
Example #10
Source File: Account.java    From fiat with Apache License 2.0 5 votes vote down vote up
public View(Account account, Set<Role> userRoles, boolean isAdmin) {
  this.name = account.name;
  if (isAdmin) {
    this.authorizations = Authorization.ALL;
  } else {
    this.authorizations = account.permissions.getAuthorizations(userRoles);
  }
}
 
Example #11
Source File: Permissions.java    From fiat with Apache License 2.0 5 votes vote down vote up
public Set<Authorization> getAuthorizations(List<String> userRoles) {
  if (!isRestricted()) {
    return Authorization.ALL;
  }

  return this.permissions.entrySet().stream()
      .filter(entry -> !Collections.disjoint(entry.getValue(), userRoles))
      .map(Map.Entry::getKey)
      .collect(Collectors.toSet());
}
 
Example #12
Source File: BuildService.java    From fiat with Apache License 2.0 5 votes vote down vote up
public View(BuildService buildService, Set<Role> userRoles, boolean isAdmin) {
  this.name = buildService.name;
  if (isAdmin) {
    this.authorizations = Authorization.ALL;
  } else {
    this.authorizations = buildService.permissions.getAuthorizations(userRoles);
  }
}
 
Example #13
Source File: AbstractAddSearchCommand.java    From halyard with Apache License 2.0 5 votes vote down vote up
@Override
protected void executeThis() {
  String searchName = getSearchName();
  Search search = buildSearch(searchName);
  String repositoryName = getRepositoryName();
  search.getPermissions().add(Authorization.READ, readPermissions);
  search.getPermissions().add(Authorization.WRITE, writePermissions);

  String currentDeployment = getCurrentDeployment();
  new OperationHandler<Void>()
      .setOperation(Daemon.addSearch(currentDeployment, repositoryName, !noValidate, search))
      .setSuccessMessage("Added " + searchName + " for " + repositoryName + ".")
      .setFailureMesssage("Failed to add " + searchName + " for " + repositoryName + ".")
      .get();
}
 
Example #14
Source File: AbstractAddMasterCommand.java    From halyard with Apache License 2.0 5 votes vote down vote up
@Override
protected void executeThis() {
  String masterName = getMasterName();
  CIAccount account = buildMaster(masterName);
  String ciName = getCiName();
  account.getPermissions().add(Authorization.READ, readPermissions);
  account.getPermissions().add(Authorization.WRITE, writePermissions);

  String currentDeployment = getCurrentDeployment();
  new OperationHandler<Void>()
      .setOperation(Daemon.addMaster(currentDeployment, ciName, !noValidate, account))
      .setSuccessMessage("Added " + masterName + " for " + ciName + ".")
      .setFailureMesssage("Failed to add " + masterName + " for " + ciName + ".")
      .get();
}
 
Example #15
Source File: ChaosMonkeyApplicationResourcePermissionSource.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Permissions getPermissions(@Nonnull Application application) {
  Permissions.Builder builder = new Permissions.Builder();
  Permissions permissions = application.getPermissions();

  if (permissions.isRestricted()) {
    if (isChaosMonkeyEnabled(application)) {
      builder.add(Authorization.READ, roles).add(Authorization.WRITE, roles).build();
    }
  }

  return builder.build();
}
 
Example #16
Source File: AggregatingResourcePermissionProvider.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Permissions getPermissions(@Nonnull T resource) {
  Permissions.Builder builder = new Permissions.Builder();
  for (ResourcePermissionSource<T> source : resourcePermissionSources) {
    Permissions permissions = source.getPermissions(resource);
    if (permissions.isRestricted()) {
      for (Authorization auth : Authorization.values()) {
        builder.add(auth, permissions.get(auth));
      }
    }
  }

  return builder.build();
}
 
Example #17
Source File: ResourcePrefixPermissionSource.java    From fiat with Apache License 2.0 5 votes vote down vote up
private Permissions getAggregatePermissions(List<PrefixEntry<T>> matchingPrefixes) {
  Permissions.Builder builder = new Permissions.Builder();
  for (PrefixEntry<T> prefix : matchingPrefixes) {
    Permissions permissions = prefix.getPermissions();
    if (permissions.isRestricted()) {
      for (Authorization auth : Authorization.values()) {
        builder.add(auth, permissions.get(auth));
      }
    }
  }

  return builder.build();
}
 
Example #18
Source File: ChaosMonkeyEventListener.java    From front50 with Apache License 2.0 5 votes vote down vote up
/**
 * We only want to add the chaos monkey role if it's missing from the permission and the
 * permission is not otherwise empty.
 */
private boolean shouldAdd(
    Application.Permission updatedPermission, Authorization authorizationType) {
  return !updatedPermission
          .getPermissions()
          .get(authorizationType)
          .contains(properties.getUserRole())
      && !updatedPermission.getPermissions().get(authorizationType).isEmpty();
}
 
Example #19
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
public Builder add(Authorization a, String group) {
  this.computeIfAbsent(a, ignored -> new ArrayList<>()).add(group);
  return this;
}
 
Example #20
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
public Map<Authorization, List<String>> unpack() {
  return Arrays.stream(Authorization.values()).collect(toMap(identity(), this::get));
}
 
Example #21
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
public Builder add(Authorization a, List<String> groups) {
  groups.forEach(group -> add(a, group));
  return this;
}
 
Example #22
Source File: ChaosMonkeyEventListener.java    From front50 with Apache License 2.0 4 votes vote down vote up
/** We only want to remove chaos monkey permissions if it is the only permission. */
private boolean shouldRemove(
    Application.Permission updatedPermission, Authorization authorizationType) {
  return updatedPermission.getPermissions().get(authorizationType).stream()
      .allMatch(it -> it.equals(properties.getUserRole()));
}
 
Example #23
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
public Builder set(Map<Authorization, List<String>> p) {
  this.clear();
  this.putAll(p);
  return this;
}
 
Example #24
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
@JsonCreator
public static Builder factory(Map<Authorization, List<String>> data) {
  return new Builder().set(data);
}
 
Example #25
Source File: FiatPermissionEvaluator.java    From fiat with Apache License 2.0 4 votes vote down vote up
private boolean permissionContains(
    UserPermission.View permission,
    String resourceName,
    ResourceType resourceType,
    Authorization authorization) {
  if (permission == null) {
    return false;
  }

  if (permission.isAdmin()) {
    // grant access regardless of whether an explicit permission to the resource exists
    return true;
  }

  Function<Set<? extends Authorizable>, Boolean> containsAuth =
      resources ->
          resources.stream()
              .anyMatch(
                  view -> {
                    Set<Authorization> authorizations =
                        Optional.ofNullable(view.getAuthorizations())
                            .orElse(Collections.emptySet());

                    return view.getName().equalsIgnoreCase(resourceName)
                        && authorizations.contains(authorization);
                  });

  if (resourceType.equals(ResourceType.ACCOUNT)) {
    boolean authorized = containsAuth.apply(permission.getAccounts());

    // Todo(jonsie): Debug transitory access denied issue, remove when not necessary
    if (!authorized) {
      Map<String, Set<Authorization>> accounts =
          permission.getAccounts().stream()
              .collect(Collectors.toMap(Account.View::getName, Account.View::getAuthorizations));

      log.debug(
          "Authorization={} denied to account={} for user permission={}, found={}",
          authorization.toString(),
          resourceName,
          permission.getName(),
          accounts.toString());
    }

    return authorized;
  } else if (resourceType.equals(ResourceType.APPLICATION)) {
    boolean applicationHasPermissions =
        permission.getApplications().stream()
            .anyMatch(a -> a.getName().equalsIgnoreCase(resourceName));

    if (!applicationHasPermissions && permission.isAllowAccessToUnknownApplications()) {
      // allow access to any applications w/o explicit permissions
      return true;
    }
    return permission.isLegacyFallback() || containsAuth.apply(permission.getApplications());
  } else if (resourceType.equals(ResourceType.SERVICE_ACCOUNT)) {
    return permission.getServiceAccounts().stream()
        .anyMatch(view -> view.getName().equalsIgnoreCase(resourceName));
  } else if (resourceType.equals(ResourceType.BUILD_SERVICE)) {
    return permission.isLegacyFallback() || containsAuth.apply(permission.getBuildServices());
  } else if (permission.getExtensionResources() != null
      && permission.getExtensionResources().containsKey(resourceType)) {
    val extensionResources = permission.getExtensionResources().get(resourceType);
    return permission.isLegacyFallback() || containsAuth.apply(extensionResources);
  } else {
    return false;
  }
}
 
Example #26
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
public List<String> get(Authorization a) {
  return permissions.getOrDefault(a, new ArrayList<>());
}
 
Example #27
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
public Set<Authorization> getAuthorizations(Set<Role> userRoles) {
  val r = userRoles.stream().map(Role::getName).collect(Collectors.toList());
  return getAuthorizations(r);
}
 
Example #28
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
/** Here specifically for Jackson serialization. */
@JsonValue
private Map<Authorization, List<String>> getPermissions() {
  return permissions;
}
 
Example #29
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
/**
 * Specifically here for Jackson deserialization. Sends data through the {@link Builder} in order
 * to sanitize the input data (just in case).
 */
@JsonCreator
public static Permissions factory(Map<Authorization, List<String>> data) {
  return new Builder().set(data).build();
}
 
Example #30
Source File: Permissions.java    From fiat with Apache License 2.0 4 votes vote down vote up
private Permissions(Map<Authorization, List<String>> p) {
  this.permissions = Collections.unmodifiableMap(p);
}