Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Security functions #235

Open
wants to merge 6 commits into
base: v0.22.0-old
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/components/security-functions/function-form/FunctionForm.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React from "react"
import { Modal, Input, Form, Row, Col, Button } from 'antd';
import FormItemLabel from "../../form-item-label/FormItemLabel"
import { MinusCircleFilled, PlusOutlined } from "@ant-design/icons";

const FunctionForm = ({ handleSubmit, handleCancel, initialValues }) => {
const [form] = Form.useForm();

const onSubmit = e => {
form.validateFields().then(values => {
values.variables = values.variables ? values.variables : []
handleSubmit(values).then(() => {
handleCancel();
form.resetFields();
})
});
}

return (
<Modal
title={`${initialValues ? "Edit" : "Add"} security function`}
okText={initialValues ? "Save" : "Add"}
visible={true}
onCancel={handleCancel}
onOk={onSubmit}
>
<Form layout="vertical" form={form} onFinish={onSubmit} initialValues={initialValues}>
<FormItemLabel name="Function name" />
<Form.Item name="id" rules={[{ required: true, message: "Please enter function name!" }]}>
<Input placeholder="e.g. create" disabled={initialValues ? true : false} />
</Form.Item>
<FormItemLabel name="Variables" />
<Form.List name="variables">
{(fields, { add, remove }) => (
<div>
{fields.map((field => (
<Row key={field.key} gutter={24}>
<Col span={20}>
<Form.Item
{...field}
rules={[
{ required: true, message: 'Please enter variable!' },
]}
>
<Input placeholder="Variable name" />
</Form.Item>
</Col>
<Col span={4}>
<MinusCircleFilled style={{ fontSize: 20, cursor: "pointer", marginTop: 5 }} onClick={() => remove(field.name)} />
</Col>
</Row>
)))}
<Button onClick={() => add()}><PlusOutlined /> {fields.length === 0 ? "Add variable" : "Add another variable"}</Button>
</div>
)}
</Form.List>
</Form>
</Modal>
);
}

export default FunctionForm;

52 changes: 49 additions & 3 deletions src/components/security-rules/configure-rule/ConfigureRule.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { getCollectionSchema, getDbConfigs, getTrackedCollections } from '../../
import { securityRuleGroups } from '../../../constants';
import JSONCodeMirror from '../../json-code-mirror/JSONCodeMirror';
import AntCodeMirror from "../../ant-code-mirror/AntCodeMirror";
import { getSecurityFunctions } from '../../../operations/securityFunctions';

const { Option } = Select;

Expand Down Expand Up @@ -155,7 +156,12 @@ const isTypeOfFieldsString = (fields) => {
return typeof fields === "string"
}

const rules = ['allow', 'deny', 'authenticated', 'match', 'and', 'or', 'query', 'webhook', 'force', 'remove', 'encrypt', 'decrypt', 'hash'];
const getSecurityFunctionVariables = (securityFunctions, functionId) => {
const index = securityFunctions.findIndex(item => item.id === functionId)
return index === -1 ? [] : securityFunctions[index].variables
}

const rules = ['allow', 'deny', 'authenticated', 'match', 'and', 'or', 'query', 'webhook', 'force', 'remove', 'encrypt', 'decrypt', 'hash', 'function'];

const ConfigureRule = (props) => {
// form
Expand All @@ -165,12 +171,13 @@ const ConfigureRule = (props) => {
const [col, setCol] = useState('');

// Derived properties
const { rule, type, f1, f2, error, fields, field, value, url, store, outputFormat, claims, requestTemplate, db, cache } = props.selectedRule;
const { rule, type, f1, f2, error, fields, field, value, url, store, outputFormat, claims, requestTemplate, db, cache, securityFunctionName, fnBlockVariables } = props.selectedRule;
const dbConfigs = useSelector(state => getDbConfigs(state))
const dbList = Object.keys(dbConfigs)
const [selectedDb, setSelectedDb] = useState(db);
const data = useSelector(state => getTrackedCollections(state, selectedDb))
const collectionSchemaString = useSelector(state => getCollectionSchema(state, props.ruleMetaData.group, props.ruleMetaData.id))
const securityFunctions = useSelector(state => getSecurityFunctions(state))

// Handlers
const handleSelectDatabase = (value) => setSelectedDb(value);
Expand Down Expand Up @@ -215,6 +222,8 @@ const ConfigureRule = (props) => {

delete values["applyTransformations"]
break;
case "function":
break;
}

delete values.errorMsg;
Expand Down Expand Up @@ -277,6 +286,7 @@ const ConfigureRule = (props) => {
autoCompleteOptions = { args: { data: true } }
break;
case securityRuleGroups.INGRESS_ROUTES:
case securityRuleGroups.SECURITY_FUNCTIONS:
const query = {
path: true,
pathArray: true,
Expand Down Expand Up @@ -312,7 +322,9 @@ const ConfigureRule = (props) => {
error,
cacheResponse: cache ? true : false,
cacheTTL: cache && cache.ttl !== undefined && cache.ttl !== null ? cache.ttl : undefined,
cacheInstantInvalidate: cache && cache.instantInvalidate !== undefined && cache.instantInvalidate !== null ? cache.instantInvalidate : undefined
cacheInstantInvalidate: cache && cache.instantInvalidate !== undefined && cache.instantInvalidate !== null ? cache.instantInvalidate : undefined,
securityFunctionName,
fnBlockVariables
}

if (formInitialValues.type === "object") {
Expand Down Expand Up @@ -685,6 +697,40 @@ const ConfigureRule = (props) => {
</ConditionalFormBlock>
</ConditionalFormBlock>
</ConditionalFormBlock>
<ConditionalFormBlock
dependency='rule'
condition={() => form.getFieldValue('rule') === 'function'}
>
<FormItemLabel name="Function name" />
<Form.Item name="securityFunctionName">
<Select placeholder="Function name">
{securityFunctions.map(item => <Select.Option value={item.id}>{item.id}</Select.Option>)}
</Select>
</Form.Item>
<Form.Item shouldUpdate>
{() => (
<React.Fragment>
{form.getFieldValue("securityFunctionName") && (
<>
<FormItemLabel name="Fields of template" />
{getSecurityFunctionVariables(securityFunctions, form.getFieldValue("securityFunctionName")).map(item => (
<Row gutter={24}>
<Col span={12}>
<Input value={item} disabled />
</Col>
<Col span={12}>
<FormItem name={["fnBlockVariables", item]} rules={[{ required: true }, { validator: createValueAndTypeValidator("variable", false), validateTrigger: "onBlur" }]}>
<ObjectAutoComplete placeholder="Value" options={autoCompleteOptions} />
</FormItem>
</Col>
</Row>
))}
</>
)}
</React.Fragment>
)}
</Form.Item>
</ConditionalFormBlock>
<FormItemLabel name='Customize error message' />
<Form.Item name='errorMsg' valuePropName='checked'>
<Checkbox checked={error ? true : false}>
Expand Down
40 changes: 38 additions & 2 deletions src/components/security-rules/graph-editor/GraphEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import dotProp from 'dot-prop-immutable';
import KeyboardEventHandler from 'react-keyboard-event-handler';
import ConfigureRule from '../configure-rule/ConfigureRule';
import SecurityRulesGraph from "../security-rules-graph/SecurityRulesGraph";
import { saveObjectToLocalStorage, getObjectFromLocalStorage } from "../../../utils";
import { saveObjectToLocalStorage, getObjectFromLocalStorage, incrementPendingRequests, notify, decrementPendingRequests } from "../../../utils";
import generateGraph from "./generateGraph";
import { securityRuleGroups, actionQueuedMessage } from "../../../constants";
import FunctionForm from "../../security-functions/function-form/FunctionForm";
import { useSelector } from "react-redux";
import { getSecurityFunction, saveSecurityFunction } from "../../../operations/securityFunctions";

const LOCAL_STORAGE_RULE_KEY = "securityRuleBuilder:copiedRule"

Expand All @@ -19,13 +23,17 @@ const getDoubleClickedRuleObject = (rule, ruleKey) => {
return dotProp.get(rule, getStrippedKey(ruleKey), {})
}

function GraphEditor({ rule, setRule, ruleName, ruleMetaData, isCachingEnabled }) {
function GraphEditor({ rule, setRule, ruleName, ruleMetaData, isCachingEnabled, projectId }) {
const { ruleType } = ruleMetaData

// Global state
const securityFunctionConfig = useSelector(state => getSecurityFunction(state, ruleName))

// Component state
const [selectedNodeId, setselectedNodeId] = useState();
const [doubleClickedNodeId, setDoubleClickedNodeId] = useState("");
const [network, setNetwork] = useState();
const [securityFunctionModal, setSecurityFunctionModal] = useState(false);

useEffect(() => {
function handleResize() {
Expand Down Expand Up @@ -69,6 +77,10 @@ function GraphEditor({ rule, setRule, ruleName, ruleMetaData, isCachingEnabled }
},
doubleClick: function (event) {
const nodeId = event.nodes[0];
if (nodeId && nodeId.startsWith("root") && ruleType === securityRuleGroups.SECURITY_FUNCTIONS) {
setSecurityFunctionModal(true);
return;
}
if (nodeId && nodeId.startsWith("root")) {
message.error("Operation not allowed. Only rule blocks (blue ones) can be double clicked to configure them")
return
Expand Down Expand Up @@ -185,6 +197,23 @@ function GraphEditor({ rule, setRule, ruleName, ruleMetaData, isCachingEnabled }
setRule(dotProp.set(rule, getStrippedKey(doubleClickedNodeId), values));
};

// On security function submit
const handleSecurityFunctionSubmit = (values) => {
return new Promise((resolve, reject) => {
incrementPendingRequests()
saveSecurityFunction(projectId, values)
.then(({ queued }) => {
notify("success", "Success", queued ? actionQueuedMessage : `Modified security function successfully`)
resolve()
})
.catch(error => {
notify("error", error.title, error.msg.length === 0 ? "Failed to set security function" : error.msg)
reject()
})
.finally(() => decrementPendingRequests())
})
}

const menu = (
<Menu onClick={({ key }) => shortcutsHandler(key)}>
<Menu.Item key='ctrl+c'>Copy</Menu.Item>
Expand Down Expand Up @@ -243,6 +272,13 @@ function GraphEditor({ rule, setRule, ruleName, ruleMetaData, isCachingEnabled }
isCachingEnabled={isCachingEnabled}
/>
)}
{securityFunctionModal && (
<FunctionForm
initialValues={securityFunctionConfig}
handleSubmit={handleSecurityFunctionSubmit}
handleCancel={() => setSecurityFunctionModal(false)}
/>
)}
</React.Fragment>
)
}
Expand Down
6 changes: 6 additions & 0 deletions src/components/security-rules/graph-editor/generateGraph.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const mergeGraph = (graph1, graph2) => {
}

const convertRuleToGraph = (rule, id, parentId) => {
console.log("RULEE", rule)
let graph = { nodes: [], edges: [] }

const isRootBlock = !parentId.includes(".")
Expand All @@ -19,6 +20,11 @@ const convertRuleToGraph = (rule, id, parentId) => {
}
return graph
}
if (rule.rule === "function") {
graph.nodes.push({ id: id, label: rule.securityFunctionName, group: "rule" })
graph.edges.push({ from: parentId, to: id })
return graph
}

graph.nodes.push({ id: id, label: rule.rule, group: "rule" })
graph.edges.push({ from: parentId, to: id })
Expand Down
3 changes: 3 additions & 0 deletions src/components/sidenav/Sidenav.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ const Sidenav = (props) => {
<Link to={`/mission-control/projects/${projectID}/${projectModules.USER_MANAGEMENT}`} onClick={closeSidenav}>
<SidenavItem name="Auth" icon="how_to_reg" active={props.selectedItem === projectModules.USER_MANAGEMENT} />
</Link>
<Link to={`/mission-control/projects/${projectID}/${projectModules.SECURITY_FUNCTIONS}`} onClick={closeSidenav}>
<SidenavItem name="Security" icon="lock" active={props.selectedItem === projectModules.SECURITY_FUNCTIONS} />
</Link>
<Link to={`/mission-control/projects/${projectID}/${projectModules.INTEGRATIONS}`} onClick={closeSidenav}>
<SidenavItem name="Integrations" icon="extension" active={props.selectedItem === projectModules.INTEGRATIONS} />
</Link>
Expand Down
10 changes: 8 additions & 2 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ export const projectModules = {
INTEGRATIONS: "integrations",
EXPLORER: "explorer",
SETTINGS: "settings",
SECURITY_RULES: "security-rules"
SECURITY_RULES: "security-rules",
SECURITY_FUNCTIONS: "security-functions"
}

export const moduleResources = {
Expand Down Expand Up @@ -161,7 +162,8 @@ export const securityRuleGroups = {
EVENTING: "eventing",
EVENTING_FILTERS: "eventing-filters",
REMOTE_SERVICES: "remote-services",
INGRESS_ROUTES: "ingress-routes"
INGRESS_ROUTES: "ingress-routes",
SECURITY_FUNCTIONS: "security-functions"
}

export const defaultDBRules = {
Expand Down Expand Up @@ -211,6 +213,10 @@ export const defaultPreparedQueryRule = {
rule: "allow"
}

export const defaultSecurityFunctionRule = {
rule: "allow"
}

export const deploymentStatuses = {
PENDING: "PENDING",
SUCCEEDED: "SUCCEEDED",
Expand Down
14 changes: 14 additions & 0 deletions src/mirage/fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -964,3 +964,17 @@ export const addonsConfig = {
}
}
}

export const securityFunctions = [
{
id: "Function 1",
variables: ["variable1", "variable2"],
rule: {
rule: "allow"
}
},
{
id: "Function 2",
variables: ["variable1", "variable2"]
}
]
5 changes: 5 additions & 0 deletions src/mirage/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ export function makeServer({ environment = "development" } = {}) {
this.post("/config/integrations", () => respondOk())
this.delete("/config/integrations/:integrationId", () => respondOk())

// SecurityFunctions endpoints
this.get("/config/projects/:projectId/security/function", () => respondOk({ result: fixtures.securityFunctions }))
this.post("/config/projects/:projectId/security/function/:id", () => respondOk())
this.delete("/config/projects/:projectId/security/function/:id", () => respondOk())

// Addons
this.get("/config/add-ons/rabbitmq/rabbitmq", () => respondOk({ result: [fixtures.addonsConfig.rabbitmq] }))
this.get("/config/add-ons/redis/redis", () => respondOk({ result: [fixtures.addonsConfig.redis] }))
Expand Down
Loading