Skip to content
This repository has been archived by the owner on Nov 22, 2023. It is now read-only.

Commit

Permalink
Use new update endpoint in Keywhiz client
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesse Peirce committed Dec 5, 2016
1 parent c8a8ab5 commit 7eb68a2
Show file tree
Hide file tree
Showing 15 changed files with 348 additions and 196 deletions.
Expand Up @@ -85,7 +85,7 @@ public PartialUpdateSecretRequestV2 build() {
.metadataPresent(metadataPresent) .metadataPresent(metadataPresent)
.metadata(metadata == null ? ImmutableMap.of() : ImmutableMap.copyOf(metadata)) .metadata(metadata == null ? ImmutableMap.of() : ImmutableMap.copyOf(metadata))
.expiryPresent(expiryPresent) .expiryPresent(expiryPresent)
.expiry(expiry == null ? 0 : expiry) .expiry(expiry == null ? Long.valueOf(0) : expiry)
.typePresent(typePresent) .typePresent(typePresent)
.type(Strings.nullToEmpty(type)) .type(Strings.nullToEmpty(type))
.build(); .build();
Expand Down
2 changes: 1 addition & 1 deletion cli/src/main/java/keywhiz/cli/CliMain.java
Expand Up @@ -35,7 +35,7 @@ public static void main(String[] args) throws Exception {
.put("list", new ListActionConfig()) .put("list", new ListActionConfig())
.put("describe", new DescribeActionConfig()) .put("describe", new DescribeActionConfig())
.put("add", new AddActionConfig()) .put("add", new AddActionConfig())
.put("update", new CreateOrUpdateActionConfig()) .put("update", new UpdateActionConfig())
.put("delete", new DeleteActionConfig()) .put("delete", new DeleteActionConfig())
.put("assign", new AssignActionConfig()) .put("assign", new AssignActionConfig())
.put("unassign", new UnassignActionConfig()) .put("unassign", new UnassignActionConfig())
Expand Down
2 changes: 1 addition & 1 deletion cli/src/main/java/keywhiz/cli/CommandExecutor.java
Expand Up @@ -135,7 +135,7 @@ public void executeCommand() throws IOException {
break; break;


case UPDATE: case UPDATE:
new CreateOrUpdateAction((CreateOrUpdateActionConfig) commands.get(command), client, mapper).run(); new UpdateAction((UpdateActionConfig) commands.get(command), client, mapper).run();
break; break;


case DELETE: case DELETE:
Expand Down
78 changes: 13 additions & 65 deletions cli/src/main/java/keywhiz/cli/commands/AddAction.java
Expand Up @@ -16,7 +16,6 @@


package keywhiz.cli.commands; package keywhiz.cli.commands;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
Expand All @@ -29,7 +28,6 @@
import keywhiz.cli.configs.AddActionConfig; import keywhiz.cli.configs.AddActionConfig;
import keywhiz.client.KeywhizClient; import keywhiz.client.KeywhizClient;
import keywhiz.client.KeywhizClient.NotFoundException; import keywhiz.client.KeywhizClient.NotFoundException;
import org.joda.time.DateTime;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;


Expand All @@ -40,27 +38,27 @@
public class AddAction implements Runnable { public class AddAction implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(AddAction.class); private static final Logger logger = LoggerFactory.getLogger(AddAction.class);


private final AddActionConfig addActionConfig; private final AddActionConfig config;
private final KeywhizClient keywhizClient; private final KeywhizClient keywhizClient;
private final ObjectMapper mapper; private final ObjectMapper mapper;


InputStream stream = System.in; InputStream stream = System.in;


public AddAction(AddActionConfig addActionConfig, KeywhizClient client, ObjectMapper mapper) { public AddAction(AddActionConfig config, KeywhizClient client, ObjectMapper mapper) {
this.addActionConfig = addActionConfig; this.config = config;
this.keywhizClient = client; this.keywhizClient = client;
this.mapper = mapper; this.mapper = mapper;
} }


@Override public void run() { @Override public void run() {
List<String> types = addActionConfig.addType; List<String> types = config.addType;


if (types == null || types.isEmpty()) { if (types == null || types.isEmpty()) {
throw new IllegalArgumentException("Must specify a single type to add."); throw new IllegalArgumentException("Must specify a single type to add.");
} }


String firstType = types.get(0).toLowerCase().trim(); String firstType = types.get(0).toLowerCase().trim();
String name = addActionConfig.name; String name = config.name;


if (name == null || !validName(name)) { if (name == null || !validName(name)) {
throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN)); throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN));
Expand All @@ -77,7 +75,7 @@ public AddAction(AddActionConfig addActionConfig, KeywhizClient client, ObjectMa
throw Throwables.propagate(e); throw Throwables.propagate(e);
} }
try { try {
keywhizClient.createGroup(name, null, null); keywhizClient.createGroup(name, config.getDescription(), config.getMetadata(mapper));
logger.info("Creating group '{}'.", name); logger.info("Creating group '{}'.", name);
} catch (IOException e) { } catch (IOException e) {
throw Throwables.propagate(e); throw Throwables.propagate(e);
Expand All @@ -94,9 +92,9 @@ public AddAction(AddActionConfig addActionConfig, KeywhizClient client, ObjectMa
throw Throwables.propagate(e); throw Throwables.propagate(e);
} }
byte[] content = readSecretContent(); byte[] content = readSecretContent();
ImmutableMap<String, String> metadata = getMetadata(); ImmutableMap<String, String> metadata = config.getMetadata(mapper);


createAndAssignSecret(name, content, metadata, getExpiry()); createAndAssignSecret(name, config.getDescription(), content, metadata, config.getExpiry());
break; break;


case "client": case "client":
Expand All @@ -121,51 +119,24 @@ public AddAction(AddActionConfig addActionConfig, KeywhizClient client, ObjectMa
} }
} }


private void createAndAssignSecret(String secretName, byte[] content, private void createAndAssignSecret(String secretName, String description, byte[] content,
ImmutableMap<String, String> metadata, long expiry) { ImmutableMap<String, String> metadata, long expiry) {
try { try {
SecretDetailResponse secretResponse = keywhizClient.createSecret(secretName, "", content, metadata, expiry); SecretDetailResponse secretResponse =
keywhizClient.createSecret(secretName, description, content, metadata, expiry);
long secretId = secretResponse.id; long secretId = secretResponse.id;


logger.info("Creating secret '{}'.", secretName); logger.info("Creating secret '{}'.", secretName);


// Optionally, also assign // Optionally, also assign
if (addActionConfig.group != null) { if (config.group != null) {
assignSecret(secretId, secretName); assignSecret(secretId, secretName);
} }
} catch (IOException e) { } catch (IOException e) {
throw Throwables.propagate(e); throw Throwables.propagate(e);
} }
} }


private ImmutableMap<String, String> getMetadata() {
ImmutableMap<String, String> metadata = ImmutableMap.of();
String jsonBlob = addActionConfig.json;
if (jsonBlob != null && !jsonBlob.isEmpty()) {
TypeReference typeRef = new TypeReference<ImmutableMap<String, String>>() {};
try {
metadata = mapper.readValue(jsonBlob, typeRef);
} catch (IOException e) {
throw Throwables.propagate(e);
}
validateMetadata(metadata);
}
return metadata;
}

private long getExpiry() {
String expiry = addActionConfig.expiry;
if (expiry != null) {
try {
return Long.parseLong(expiry);
} catch (NumberFormatException e) {
}
DateTime dt = new DateTime(expiry);
return dt.getMillis()/1000;
}
return 0;
}

private byte[] readSecretContent() { private byte[] readSecretContent() {
try { try {
byte[] content = ByteStreams.toByteArray(stream); byte[] content = ByteStreams.toByteArray(stream);
Expand All @@ -178,32 +149,9 @@ private byte[] readSecretContent() {
} }
} }


private static void validateMetadata(ImmutableMap<String, String> metadata) {
for (ImmutableMap.Entry<String, String> entry : metadata.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();

// We want to perform strong validation of the metadata to make sure it is well formed.
if (!key.matches("(owner|group|mode)")) {
if(!key.startsWith("_")) {
throw new IllegalArgumentException(
format("Illegal metadata key %s: custom metadata keys must start with an underscore", key));
}
if(!key.matches("^[a-zA-Z_0-9\\-.:]+$")) {
throw new IllegalArgumentException(
format("Illegal metadata key %s: metadata keys can only contain: a-z A-Z 0-9 _ - . :", key));
}
}

if (key.equals("mode") && !value.matches("0[0-7]+")) {
throw new IllegalArgumentException(format("mode %s is not proper octal", value));
}
}
}

private void assignSecret(long secretId, String secretDisplayName) { private void assignSecret(long secretId, String secretDisplayName) {
try { try {
Group group = keywhizClient.getGroupByName(addActionConfig.group); Group group = keywhizClient.getGroupByName(config.group);
if (group == null) { if (group == null) {
throw new AssertionError("Group does not exist."); throw new AssertionError("Group does not exist.");
} }
Expand Down
83 changes: 83 additions & 0 deletions cli/src/main/java/keywhiz/cli/commands/UpdateAction.java
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package keywhiz.cli.commands;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import keywhiz.cli.configs.AddOrUpdateActionConfig;
import keywhiz.cli.configs.UpdateActionConfig;
import keywhiz.client.KeywhizClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.lang.String.format;
import static keywhiz.cli.Utilities.VALID_NAME_PATTERN;
import static keywhiz.cli.Utilities.validName;

public class UpdateAction implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(UpdateAction.class);

private final UpdateActionConfig config;
private final KeywhizClient keywhizClient;
private final ObjectMapper mapper;

InputStream stream = System.in;

public UpdateAction(UpdateActionConfig config, KeywhizClient client,
ObjectMapper mapper) {
this.config = config;
this.keywhizClient = client;
this.mapper = mapper;
}

@Override public void run() {
String secretName = config.name;

if (secretName == null || !validName(secretName)) {
throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN));
}

byte[] content = {};
if (config.contentProvided) {
content = readSecretContent();
}
partialUpdateSecret(secretName, content, config);
}

private void partialUpdateSecret(String secretName, byte[] content,
AddOrUpdateActionConfig config) {
try {
keywhizClient.updateSecret(secretName, config.description != null,
config.getDescription(), content.length > 0, content, config.json != null,
config.getMetadata(mapper), config.expiry != null, config.getExpiry());
logger.info("partialUpdate secret '{}'.", secretName);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}

private byte[] readSecretContent() {
try {
return ByteStreams.toByteArray(stream);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
}
30 changes: 1 addition & 29 deletions cli/src/main/java/keywhiz/cli/configs/AddActionConfig.java
@@ -1,39 +1,11 @@
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package keywhiz.cli.configs; package keywhiz.cli.configs;


import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import java.util.List; import java.util.List;


@Parameters(commandDescription = "Add clients, groups, or secrets to KeyWhiz") @Parameters(commandDescription = "Add clients, groups, or secrets to KeyWhiz")
public class AddActionConfig { public class AddActionConfig extends AddOrUpdateActionConfig {
@Parameter(description = "<client|group|secret>") @Parameter(description = "<client|group|secret>")
public List<String> addType; public List<String> addType;

@Parameter(names = "--name", description = "Name of the item to add", required = true)
public String name;

@Parameter(names = "--json", description = "Metadata JSON blob")
public String json;

@Parameter(names = { "-g", "--group" }, description = "Also assign the secret to this group (secrets only)")
public String group;

@Parameter(names = { "-e", "--expiry" }, description = "Secret expiry. For keystores, it is recommended to use the expiry of the earliest key. Format should be 2006-01-02T15:04:05Z or seconds since epoch.")
public String expiry;
} }

0 comments on commit 7eb68a2

Please sign in to comment.