Compare commits

..

24 Commits

Author SHA1 Message Date
Jonas Plum
02c7da91da Add Dashboards (#41) 2022-03-14 00:23:29 +01:00
Jonas Plum
18a4dc54e7 Add global settings (#40) 2022-03-13 13:45:10 +01:00
Jonas Plum
86daadc73d Cleanup content (#39) 2022-03-12 22:45:58 +01:00
Jonas Plum
687be41994 Fix artifact enrichment (#38) 2022-03-12 22:08:51 +01:00
Jonas Plum
d353268cf2 Update generator (#37) 2022-03-12 21:09:10 +01:00
Jonas Plum
eced5df7c8 Add admin user config (#36) 2022-03-01 01:01:59 +01:00
Jonas Plum
ffba7b4f5f Add test for jobs (#34) 2022-02-27 18:33:50 +01:00
Jonas Plum
fd18458f3d Remove TheHive automation (#35) 2022-02-27 15:31:17 +01:00
Jonas Plum
338aba8342 Check input schema (#33) 2022-02-27 12:25:41 +01:00
Jonas Plum
54312893a2 Fix dashboard redirect (#32) 2022-02-17 21:51:54 +01:00
Jonas Plum
599b9d3c6e Set network (#31)
* Set network for automation docker container
2022-02-13 20:44:16 +01:00
Jonas Plum
2d817318f2 Better file api (#30)
* Better file api
2022-01-23 04:27:31 +01:00
Jonas Plum
8ca57c14d9 Add handbook links (#29)
* Add handbook links
2022-01-20 11:12:29 +01:00
Jonas Plum
ad02113d99 Improve Job UI (#28) 2022-01-20 10:59:57 +01:00
Jonas Plum
6fbc6f9837 Autocreate links to other tickets (#27) 2022-01-20 10:18:45 +01:00
Jonas Plum
8e8a7ec2a2 Create three panel view (#26)
* Create three panel view
2022-01-20 10:08:37 +01:00
Jonas Plum
a152b6663b Add breadcrumb menu (#25)
* Add breadcrumbs
2022-01-19 12:05:06 +01:00
Jonas Plum
5653ecb5b0 Add timeformat edit (#6) 2022-01-19 01:30:27 +01:00
Jonas Plum
27da64a470 Change license (#5) 2022-01-19 01:00:50 +01:00
Jonas Plum
8333ea88a8 Change code generator (#4)
* Change code generator
* Remove gin
2022-01-08 00:48:44 +01:00
Jonas Plum
b5dd0cfacd Improve bus (#3)
* Improve bus
* Add ticket log
2021-12-27 19:08:07 +01:00
Jonas Plum
1fade14ba5 Mock time (#2) 2021-12-27 00:17:44 +01:00
Jonas Plum
0286574692 Add backup and restore test (#1)
* Add backup and restore test
* Update arango binaries
2021-12-24 00:22:08 +01:00
Jonas Plum
c27e61b875 Add social media links 2021-12-20 17:18:23 +01:00
223 changed files with 12838 additions and 32364 deletions

View File

@@ -26,9 +26,9 @@ jobs:
working-directory: dev
- name: Install ArangoDB
run: |
curl -OL https://download.arangodb.com/arangodb34/DEBIAN/Release.key
curl -OL https://download.arangodb.com/arangodb38/DEBIAN/Release.key
sudo apt-key add Release.key
sudo apt-add-repository 'deb https://download.arangodb.com/arangodb34/DEBIAN/ /'
sudo apt-add-repository 'deb https://download.arangodb.com/arangodb38/DEBIAN/ /'
sudo apt-get update -y && sudo apt-get -y install arangodb3
- run: go test -coverprofile=cover.out -coverpkg=./... ./...
- run: go tool cover -func=cover.out
@@ -46,6 +46,7 @@ jobs:
with: { name: ui, path: ui/dist, retention-days: 1 }
build:
if: github.event_name != 'pull_request'
name: Build
runs-on: ubuntu-latest
needs: [ build-npm, test ]

661
LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -1,104 +0,0 @@
Copyright (c) 2021-present Jonas Plum
Portions of this software are licensed as follows:
* All third party components incorporated into Catalyst are licensed under the
original license provided by the owner of the applicable component. Those
files contain a license notice on top of the file and are listed in the
[NOTICE](NOTICE) file.
* Content outside of the above mentioned files above is
available under the "Elastic License 2.0" license as defined below.
# Elastic License 2.0
URL: https://www.elastic.co/licensing/elastic-license
## Acceptance
By using the software, you agree to all of the terms and conditions below.
## Copyright License
The licensor grants you a non-exclusive, royalty-free, worldwide,
non-sublicensable, non-transferable license to use, copy, distribute, make
available, and prepare derivative works of the software, in each case subject to
the limitations and conditions below.
## Limitations
You may not provide the software to third parties as a hosted or managed
service, where the service provides users with access to any substantial set of
the features or functionality of the software.
You may not move, change, disable, or circumvent the license key functionality
in the software, and you may not remove or obscure any functionality in the
software that is protected by the license key.
You may not alter, remove, or obscure any licensing, copyright, or other notices
of the licensor in the software. Any use of the licensors trademarks is subject
to applicable law.
## Patents
The licensor grants you a license, under any patent claims the licensor can
license, or becomes able to license, to make, have made, use, sell, offer for
sale, import and have imported the software, in each case subject to the
limitations and conditions in this license. This license does not cover any
patent claims that you cause to be infringed by modifications or additions to
the software. If you or your company make any written claim that the software
infringes or contributes to infringement of any patent, your patent license for
the software granted under these terms ends immediately. If your company makes
such a claim, your patent license ends immediately for work on behalf of your
company.
## Notices
You must ensure that anyone who gets a copy of any part of the software from you
also gets a copy of these terms.
If you modify the software, you must include in any modified copies of the
software prominent notices stating that you have modified the software.
## No Other Rights
These terms do not imply any licenses other than those expressly granted in
these terms.
## Termination
If you use the software in violation of these terms, such use is not licensed,
and your licenses will automatically terminate. If the licensor provides you
with a notice of your violation, and you cease all violation of this license no
later than 30 days after you receive that notice, your licenses will be
reinstated retroactively. However, if you violate these terms after such
reinstatement, any additional violation of these terms will cause your licenses
to terminate automatically and permanently.
## No Liability
*As far as the law allows, the software comes as is, without any warranty or
condition, and the licensor will not be liable to you for any damages arising
out of these terms or the use or nature of the software, under any kind of
legal claim.*
## Definitions
The **licensor** is the entity offering these terms, and the **software** is the
software the licensor makes available under these terms, including any portion
of it.
**you** refers to the individual or entity agreeing to these terms.
**your company** is any legal entity, sole proprietorship, or other kind of
organization that you work for, plus all organizations that have control over,
are under the control of, or are under common control with that
organization. **control** means ownership of substantially all the assets of an
entity, or the power to direct its management and policies by vote, contract, or
otherwise. Control can be direct or indirect.
**your licenses** are all the licenses granted to you for the software under
these terms.
**use** means anything you do with the software requiring one of your licenses.
**trademark** means trademarks, service marks, and similar rights.

View File

@@ -7,8 +7,14 @@
-
<a href="https://catalyst-soar.com/docs/category/catalyst-handbook">The Catalyst Handbook (Documentation)</a>
-
<a href="https://try.catalyst-soar.com">Try online</a> (user: bob, password: bob)
<a href="https://try.catalyst-soar.com">Try online</a>
</h4>
<h4 align="center">
<a href="https://twitter.com/securitybrewery">Twitter</a>
-
<a href="https://discord.gg/nrmpveWvZX">Discord</a>
</h4>
Catalyst is an incident response platform or SOAR (Security Orchestration, Automation and Response) system. It can help
you to automate your alert handling and incident response procedures.
@@ -23,7 +29,7 @@ Tickets are the core of Catalyst. They represent alerts, incidents, forensics
investigations, threat hunts or any other event you want to handle in your
organisation.
## Ticket Templates
### Ticket Templates
<center>
<img width="400" alt="Screenshot of the playbook part of a ticket" src="docs/screenshots/details.png" />
@@ -34,7 +40,7 @@ tickets like title, creation date or closing status is kept quite minimal and ot
information like criticality, description or MITRE ATT&CK information can be
added individually.
## Conditional Custom Fields
### Conditional Custom Fields
<center>
<img width="400" alt="Screenshot of the playbook part of a ticket" src="docs/screenshots/conditional_custom_field_a.png" />
@@ -46,7 +52,7 @@ Custom Fields can be dependent on each other. So if you, for example choose
ransomware, worm, etc. which a "phishing" incident would ask for the number
of received mails in that campaign.
## Playbooks
### Playbooks
<center>
<img alt="Screenshot of the playbook part of a ticket" src="docs/screenshots/phishing_playbook.png" />
@@ -56,7 +62,7 @@ Playbooks represent processes that can be attached to tickets. Playbooks can
contain manual and automated tasks. Complex workflows with different workflow
branches, parallel tasks and task dependencies can be modeled.
## Automations
### Automations
<center>
<img alt="Screenshot of the playbook part of a ticket" src="docs/screenshots/script.png" />
@@ -66,7 +72,7 @@ Automations are scripts that automate tasks or enrich artifacts. Automations are
run in their own Docker containers. This enables them to be created in different
scripting languages and run securely in their own environment.
## Users
### Users
<center>
<img alt="Screenshot of the playbook part of a ticket" src="docs/screenshots/roles.png" />
@@ -76,3 +82,16 @@ Catalyst has two different types of users, normal users accessing the platform
via OIDC authentication and API keys for external script. A
fine-grained access model is available for both types and allows to define
possible actions for each user.
## License
Copyright (c) 2021-present Jonas Plum
Portions of this software are licensed as follows:
* All third party components incorporated into Catalyst are licensed under the
original license provided by the owner of the applicable component. Those
files contain a license notice on top of the file and are listed in the
[NOTICE](NOTICE) file.
* Content outside the above-mentioned files above is
available under the [GNU Affero General Public License v3.0](LICENSE).

399
auth.go
View File

@@ -4,21 +4,19 @@ import (
"context"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/hooks"
"github.com/SecurityBrewery/catalyst/role"
)
@@ -33,6 +31,7 @@ type AuthConfig struct {
OIDCClaimName string
AuthBlockNew bool
AuthDefaultRoles []role.Role
AuthAdminUsers []string
provider *oidc.Provider
}
@@ -58,188 +57,135 @@ func (c *AuthConfig) Load(ctx context.Context) error {
return nil
}
const (
SessionName = "catalyst-session"
stateSession = "state"
userSession = "user"
)
func Authenticate(db *database.Database, config *AuthConfig) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
keyHeader := r.Header.Get("PRIVATE-TOKEN")
authHeader := r.Header.Get("User")
func Authenticate(db *database.Database, config *AuthConfig) gin.HandlerFunc {
return func(ctx *gin.Context) {
iss := config.OIDCIssuer
keyHeader := ctx.Request.Header.Get("PRIVATE-TOKEN")
if keyHeader != "" {
keyAuth(db, keyHeader)(ctx)
return
}
authHeader := ctx.Request.Header.Get("User")
if authHeader != "" {
bearerAuth(db, authHeader, iss, config)(ctx)
return
}
sessionAuth(db, config)(ctx)
switch {
case keyHeader != "":
keyAuth(db, keyHeader)(next).ServeHTTP(w, r)
case authHeader != "":
iss := config.OIDCIssuer
bearerAuth(db, authHeader, iss, config)(next).ServeHTTP(w, r)
default:
sessionAuth(db, config)(next).ServeHTTP(w, r)
}
})
}
}
func oidcCtx(ctx *gin.Context) (context.Context, context.CancelFunc) {
/*
if config.TLSCertFile != "" && config.TLSKeyFile != "" {
cert, err := tls.LoadX509KeyPair(config.TLSCertFile, config.TLSKeyFile)
func bearerAuth(db *database.Database, authHeader string, iss string, config *AuthConfig) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(authHeader, "Bearer ") {
api.JSONErrorStatus(w, http.StatusUnauthorized, errors.New("no bearer token"))
return
}
claims, apiError := verifyClaims(r, config, authHeader[7:])
if apiError != nil {
api.JSONErrorStatus(w, apiError.Status, apiError.Internal)
return
}
// if claims.Iss != iss {
// return &api.HTTPError{Status: http.StatusInternalServerError, Internal: "wrong issuer"})
// return
// }
setClaimsCookie(w, claims)
r, err := setContextClaims(r, db, claims, config)
if err != nil {
return nil, err
api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not load user: %w", err))
return
}
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
for _, c := range cert.Certificate {
rootCAs.AppendCertsFromPEM(c)
}
return oidc.ClientContext(ctx, &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: rootCAs,
InsecureSkipVerify: true,
},
},
}), nil
}
*/
cctx, cancel := context.WithTimeout(ctx, time.Minute)
return cctx, cancel
}
func bearerAuth(db *database.Database, authHeader string, iss string, config *AuthConfig) func(ctx *gin.Context) {
return func(ctx *gin.Context) {
if !strings.HasPrefix(authHeader, "Bearer ") {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "no bearer token"})
return
}
oidcCtx, cancel := oidcCtx(ctx)
defer cancel()
verifier, err := config.Verifier(oidcCtx)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "could not verify: " + err.Error()})
return
}
authToken, err := verifier.Verify(oidcCtx, authHeader[7:])
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not verify bearer token: %v", err)})
return
}
var claims map[string]interface{}
if err := authToken.Claims(&claims); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to parse claims: %v", err)})
return
}
// if claims.Iss != iss {
// ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "wrong issuer"})
// return
// }
session := sessions.Default(ctx)
session.Set(userSession, claims)
if err = session.Save(); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, fmt.Sprintf("could not set session: %v", err))
return
}
if err = setContextClaims(ctx, db, claims, config); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not load user: %s", err)})
return
}
ctx.Next()
next.ServeHTTP(w, r)
})
}
}
func keyAuth(db *database.Database, keyHeader string) func(ctx *gin.Context) {
return func(ctx *gin.Context) {
h := fmt.Sprintf("%x", sha256.Sum256([]byte(keyHeader)))
func keyAuth(db *database.Database, keyHeader string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := fmt.Sprintf("%x", sha256.Sum256([]byte(keyHeader)))
key, err := db.UserByHash(ctx, h)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not verify private token: %v", err)})
return
}
key, err := db.UserByHash(r.Context(), h)
if err != nil {
api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not verify private token: %w", err))
return
}
setContextUser(ctx, key, db.Hooks)
r = setContextUser(r, key, db.Hooks)
ctx.Next()
next.ServeHTTP(w, r)
})
}
}
func sessionAuth(db *database.Database, config *AuthConfig) func(ctx *gin.Context) {
return func(ctx *gin.Context) {
session := sessions.Default(ctx)
func sessionAuth(db *database.Database, config *AuthConfig) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, noCookie, err := claimsCookie(r)
if err != nil {
api.JSONError(w, err)
return
}
if noCookie {
redirectToLogin(w, r, config.OAuth2)
return
}
user := session.Get(userSession)
if user == nil {
redirectToLogin(ctx, session, config.OAuth2)
r, err = setContextClaims(r, db, claims, config)
if err != nil {
api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("could not load user: %w", err))
return
}
return
}
claims, ok := user.(map[string]interface{})
if !ok {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "claims not in session"})
return
}
if err := setContextClaims(ctx, db, claims, config); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not load user: %s", err)})
return
}
ctx.Next()
next.ServeHTTP(w, r)
})
}
}
func setContextClaims(ctx *gin.Context, db *database.Database, claims map[string]interface{}, config *AuthConfig) error {
func setContextClaims(r *http.Request, db *database.Database, claims map[string]interface{}, config *AuthConfig) (*http.Request, error) {
newUser, newSetting, err := mapUserAndSettings(claims, config)
if err != nil {
return err
return nil, err
}
if _, ok := busdb.UserFromContext(ctx); !ok {
busdb.SetContext(ctx, &models.UserResponse{ID: "auth", Roles: []string{role.Admin}, Apikey: false, Blocked: false})
if _, ok := busdb.UserFromContext(r.Context()); !ok {
r = busdb.SetContext(r, &model.UserResponse{ID: "auth", Roles: []string{role.Admin}, Apikey: false, Blocked: false})
}
user, err := db.UserGetOrCreate(ctx, newUser)
user, err := db.UserGetOrCreate(r.Context(), newUser)
if err != nil {
return err
return nil, err
}
_, err = db.UserDataGetOrCreate(ctx, newUser.ID, newSetting)
_, err = db.UserDataGetOrCreate(r.Context(), newUser.ID, newSetting)
if err != nil {
return err
return nil, err
}
setContextUser(ctx, user, db.Hooks)
return nil
return setContextUser(r, user, db.Hooks), nil
}
func setContextUser(ctx *gin.Context, user *models.UserResponse, hooks *hooks.Hooks) {
groups, err := hooks.GetGroups(ctx, user.ID)
func setContextUser(r *http.Request, user *model.UserResponse, hooks *hooks.Hooks) *http.Request {
groups, err := hooks.GetGroups(r.Context(), user.ID)
if err == nil {
busdb.SetGroupContext(ctx, groups)
r = busdb.SetGroupContext(r, groups)
}
busdb.SetContext(ctx, user)
return busdb.SetContext(r, user)
}
func mapUserAndSettings(claims map[string]interface{}, config *AuthConfig) (*models.UserForm, *models.UserData, error) {
func mapUserAndSettings(claims map[string]interface{}, config *AuthConfig) (*model.UserForm, *model.UserData, error) {
// handle Bearer tokens
// if typ, ok := claims["typ"]; ok && typ == "Bearer" {
// return &models.User{
// return &model.User{
// Username: "bot",
// Blocked: false,
// Email: pointer.String("bot@example.org"),
@@ -262,16 +208,30 @@ func mapUserAndSettings(claims map[string]interface{}, config *AuthConfig) (*mod
name = ""
}
return &models.UserForm{
var roles = role.Strings(config.AuthDefaultRoles)
if contains(config.AuthAdminUsers, username) {
roles = append(roles, role.Admin)
}
return &model.UserForm{
ID: username,
Blocked: config.AuthBlockNew,
Roles: role.Strings(config.AuthDefaultRoles),
}, &models.UserData{
Roles: roles,
}, &model.UserData{
Email: &email,
Name: &name,
}, nil
}
func contains(l []string, s string) bool {
for _, e := range l {
if e == s {
return true
}
}
return false
}
func getString(m map[string]interface{}, key string) (string, error) {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
@@ -283,114 +243,92 @@ func getString(m map[string]interface{}, key string) (string, error) {
return "", fmt.Errorf("mapping of %s failed, missing value", key)
}
func redirectToLogin(ctx *gin.Context, session sessions.Session, oauth2Config *oauth2.Config) {
func redirectToLogin(w http.ResponseWriter, r *http.Request, oauth2Config *oauth2.Config) {
state, err := state()
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "generating state failed"})
return
}
session.Set(stateSession, state)
err = session.Save()
if err != nil {
log.Println(err)
}
ctx.Redirect(http.StatusFound, oauth2Config.AuthCodeURL(state))
log.Println("abort", ctx.Request.URL.String())
ctx.Abort()
}
func AuthorizeBlockedUser(ctx *gin.Context) {
user, ok := busdb.UserFromContext(ctx)
if !ok {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "no user in context"})
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("generating state failed"))
return
}
if user.Blocked {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "user is blocked"})
return
}
setStateCookie(w, state)
ctx.Next()
http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusFound)
return
}
func AuthorizeRole(roles []role.Role) gin.HandlerFunc {
return func(ctx *gin.Context) {
user, ok := busdb.UserFromContext(ctx)
if !ok {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "no user in context"})
return
}
func AuthorizeBlockedUser() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := busdb.UserFromContext(r.Context())
if !ok {
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("no user in context"))
return
}
if !role.UserHasRoles(user, roles) {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": fmt.Sprintf("missing role %s has %s", roles, user.Roles)})
return
}
if user.Blocked {
api.JSONErrorStatus(w, http.StatusForbidden, errors.New("user is blocked"))
return
}
ctx.Next()
next.ServeHTTP(w, r)
})
}
}
func callback(config *AuthConfig) gin.HandlerFunc {
return func(ctx *gin.Context) {
session := sessions.Default(ctx)
func AuthorizeRole(roles []string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := busdb.UserFromContext(r.Context())
if !ok {
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("no user in context"))
return
}
state := session.Get(stateSession)
if state == "" {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "state missing"})
if !role.UserHasRoles(user, role.FromStrings(roles)) {
api.JSONErrorStatus(w, http.StatusForbidden, fmt.Errorf("missing role %s has %s", roles, user.Roles))
return
}
next.ServeHTTP(w, r)
})
}
}
func callback(config *AuthConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
state, err := stateCookie(r)
if err != nil || state == "" {
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("state missing"))
return
}
if state != ctx.Query("state") {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "state mismatch"})
if state != r.URL.Query().Get("state") {
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("state mismatch"))
return
}
oauth2Token, err := config.OAuth2.Exchange(ctx, ctx.Query("code"))
oauth2Token, err := config.OAuth2.Exchange(r.Context(), r.URL.Query().Get("code"))
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": gin.H{"error": fmt.Sprintf("oauth2 exchange failed: %s", err)}})
api.JSONErrorStatus(w, http.StatusInternalServerError, fmt.Errorf("oauth2 exchange failed: %w", err))
return
}
// Extract the ID Token from OAuth2 token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "missing id token"})
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("missing id token"))
return
}
oidcCtx, cancel := oidcCtx(ctx)
defer cancel()
verifier, err := config.Verifier(oidcCtx)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "could not verify: " + err.Error()})
claims, apiError := verifyClaims(r, config, rawIDToken)
if apiError != nil {
api.JSONErrorStatus(w, apiError.Status, apiError.Internal)
return
}
// Parse and verify ID Token payload.
idToken, err := verifier.Verify(oidcCtx, rawIDToken)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "token verification failed: " + err.Error()})
return
}
setClaimsCookie(w, claims)
// Extract custom claims
var claims map[string]interface{}
if err := idToken.Claims(&claims); err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "claim extraction failed"})
return
}
session.Set(userSession, claims)
err = session.Save()
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not save session %s", err)})
return
}
ctx.Redirect(http.StatusFound, "/")
http.Redirect(w, r, "/", http.StatusFound)
}
}
@@ -401,3 +339,20 @@ func state() (string, error) {
}
return base64.URLEncoding.EncodeToString(rnd), nil
}
func verifyClaims(r *http.Request, config *AuthConfig, rawIDToken string) (map[string]interface{}, *api.HTTPError) {
verifier, err := config.Verifier(r.Context())
if err != nil {
return nil, &api.HTTPError{Status: http.StatusUnauthorized, Internal: fmt.Errorf("could not verify: %w", err)}
}
authToken, err := verifier.Verify(r.Context(), rawIDToken)
if err != nil {
return nil, &api.HTTPError{Status: http.StatusInternalServerError, Internal: fmt.Errorf("could not verify bearer token: %w", err)}
}
var claims map[string]interface{}
if err := authToken.Claims(&claims); err != nil {
return nil, &api.HTTPError{Status: http.StatusInternalServerError, Internal: fmt.Errorf("failed to parse claims: %w", err)}
}
return claims, nil
}

View File

@@ -1,26 +0,0 @@
package automation
import (
"context"
"log"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/role"
)
func New(apiurl, apikey string, bus *bus.Bus, db *database.Database) error {
if err := jobAutomation(jobContext(), apiurl, apikey, bus, db); err != nil {
log.Fatal(err)
}
return resultAutomation(bus, db)
}
func jobContext() context.Context {
// TODO: change roles?
bot := &models.UserResponse{ID: "bot", Roles: []string{role.Admin}}
return busdb.UserContext(context.Background(), bot)
}

View File

@@ -1,116 +0,0 @@
package automation
import (
"encoding/json"
"fmt"
"log"
"golang.org/x/net/context"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/generated/models"
)
func jobAutomation(ctx context.Context, apiurl, apikey string, catalystBus *bus.Bus, db *database.Database) error {
return catalystBus.SubscribeJob(func(automationMsg *bus.JobMsg) {
job, err := db.JobCreate(ctx, automationMsg.ID, &models.JobForm{
Automation: automationMsg.Automation,
Payload: automationMsg.Message.Payload,
Origin: automationMsg.Origin,
})
if err != nil {
log.Println(err)
return
}
automation, err := db.AutomationGet(ctx, automationMsg.Automation)
if err != nil {
log.Println(err)
return
}
if automation.Script == "" {
log.Println("automation is empty")
return
}
if automationMsg.Message.Secrets == nil {
automationMsg.Message.Secrets = map[string]string{}
}
automationMsg.Message.Secrets["catalyst_apikey"] = apikey
automationMsg.Message.Secrets["catalyst_apiurl"] = apiurl
scriptMessage, _ := json.Marshal(automationMsg.Message)
containerID, logs, err := createContainer(ctx, automation.Image, automation.Script, string(scriptMessage))
if err != nil {
log.Println(err)
return
}
if _, err := db.JobUpdate(ctx, automationMsg.ID, &models.Job{
Automation: job.Automation,
Container: &containerID,
Origin: job.Origin,
Output: job.Output,
Log: &logs,
Payload: job.Payload,
Status: job.Status,
}); err != nil {
log.Println(err)
return
}
var result map[string]interface{}
stdout, _, err := runDocker(ctx, automationMsg.ID, containerID, db)
if err != nil {
result = map[string]interface{}{"error": fmt.Sprintf("error running script %s %s", err, string(stdout))}
} else {
var data map[string]interface{}
if err := json.Unmarshal(stdout, &data); err != nil {
result = map[string]interface{}{"error": string(stdout)}
} else {
result = data
}
}
if err := catalystBus.PublishResult(automationMsg.Automation, result, automationMsg.Origin); err != nil {
log.Println(err)
}
if err := db.JobComplete(ctx, automationMsg.ID, result); err != nil {
log.Println(err)
return
}
})
}
/*
func getAutomation(automationID string, config *Config) (*models.AutomationResponse, error) {
req, err := http.NewRequest(http.MethodGet, config.CatalystAPIUrl+"/automations/"+automationID, nil)
if err != nil {
return nil, err
}
req.Header.Set("PRIVATE-TOKEN", config.CatalystAPIKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var automation models.AutomationResponse
if err := json.Unmarshal(b, &automation); err != nil {
return nil, err
}
return &automation, nil
}
*/

View File

@@ -1,38 +0,0 @@
package automation
import (
"log"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/generated/models"
)
func resultAutomation(catalystBus *bus.Bus, db *database.Database) error {
return catalystBus.SubscribeResult(func(resultMsg *bus.ResultMsg) {
if resultMsg.Target != nil {
ctx := jobContext()
switch {
case resultMsg.Target.TaskOrigin != nil:
if _, err := db.TaskComplete(
ctx,
resultMsg.Target.TaskOrigin.TicketId,
resultMsg.Target.TaskOrigin.PlaybookId,
resultMsg.Target.TaskOrigin.TaskId,
resultMsg.Data,
); err != nil {
log.Println(err)
}
case resultMsg.Target.ArtifactOrigin != nil:
enrichment := &models.EnrichmentForm{
Data: resultMsg.Data,
Name: resultMsg.Automation,
}
_, err := db.EnrichArtifact(ctx, resultMsg.Target.ArtifactOrigin.TicketId, resultMsg.Target.ArtifactOrigin.Artifact, enrichment)
if err != nil {
log.Println(err)
}
}
}
})
}

View File

@@ -5,7 +5,6 @@ import (
"bytes"
"io"
"io/fs"
"log"
"net/http"
"os"
"os/exec"
@@ -13,20 +12,19 @@ import (
"strings"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/storage"
)
func BackupHandler(catalystStorage *storage.Storage, c *database.Config) gin.HandlerFunc {
return func(context *gin.Context) {
context.Header("Content-Disposition", "attachment; filename=backup.zip")
context.Header("Content-Type", "application/zip")
err := Backup(catalystStorage, c, context.Writer)
func backupHandler(catalystStorage *storage.Storage, c *database.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", "attachment; filename=backup.zip")
w.Header().Set("Content-Type", "application/zip")
err := Backup(catalystStorage, c, w)
if err != nil {
log.Println(err)
context.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
api.JSONError(w, err)
}
}
}
@@ -59,6 +57,7 @@ func backupS3(catalystStorage *storage.Storage, archive *zip.Writer) error {
if err != nil {
return err
}
for _, bucket := range buckets.Buckets {
objects, err := catalystStorage.S3().ListObjectsV2(&s3.ListObjectsV2Input{
Bucket: bucket.Name,

View File

@@ -4,16 +4,7 @@ import (
"encoding/json"
"log"
"github.com/arangodb/go-driver"
emitter "github.com/emitter-io/go/v2"
"github.com/SecurityBrewery/catalyst/generated/models"
)
const (
channelUpdate = "data"
channelJob = "job"
channelResult = "result"
)
type Bus struct {
@@ -22,25 +13,13 @@ type Bus struct {
}
type Config struct {
Host string
Key string
resultBusKey string
jobBusKey string
dataBusKey string
APIUrl string
}
type JobMsg struct {
ID string `json:"id"`
Automation string `json:"automation"`
Origin *models.Origin `json:"origin"`
Message *models.Message `json:"message"`
}
type ResultMsg struct {
Automation string `json:"automation"`
Data map[string]interface{} `json:"data,omitempty"`
Target *models.Origin `json:"target"`
Host string
Key string
databaseUpdateBusKey string
jobBusKey string
resultBusKey string
requestKey string
APIUrl string
}
func New(c *Config) (*Bus, error) {
@@ -51,7 +30,7 @@ func New(c *Config) (*Bus, error) {
return nil, err
}
c.dataBusKey, err = client.GenerateKey(c.Key, channelUpdate+"/", "rwls", 0)
c.databaseUpdateBusKey, err = client.GenerateKey(c.Key, channelDatabaseUpdate+"/", "rwls", 0)
if err != nil {
return nil, err
}
@@ -63,30 +42,14 @@ func New(c *Config) (*Bus, error) {
if err != nil {
return nil, err
}
c.requestKey, err = client.GenerateKey(c.Key, ChannelRequest+"/", "rwls", 0)
if err != nil {
return nil, err
}
return &Bus{config: c, client: client}, err
}
func (b *Bus) PublishUpdate(ids []driver.DocumentID) error {
return b.jsonPublish(ids, channelUpdate, b.config.dataBusKey)
}
func (b *Bus) PublishJob(id, automation string, payload interface{}, context *models.Context, origin *models.Origin) error {
return b.jsonPublish(&JobMsg{
ID: id,
Automation: automation,
Origin: origin,
Message: &models.Message{
Context: context,
Payload: payload,
},
}, channelJob, b.config.jobBusKey)
}
func (b *Bus) PublishResult(automation string, data map[string]interface{}, target *models.Origin) error {
return b.jsonPublish(&ResultMsg{Automation: automation, Data: data, Target: target}, channelResult, b.config.resultBusKey)
}
func (b *Bus) jsonPublish(msg interface{}, channel, key string) error {
payload, err := json.Marshal(msg)
if err != nil {
@@ -96,39 +59,6 @@ func (b *Bus) jsonPublish(msg interface{}, channel, key string) error {
return b.client.Publish(key, channel, payload)
}
func (b *Bus) SubscribeUpdate(f func(ids []driver.DocumentID)) error {
return b.safeSubscribe(b.config.dataBusKey, channelUpdate, func(c *emitter.Client, m emitter.Message) {
var msg []driver.DocumentID
if err := json.Unmarshal(m.Payload(), &msg); err != nil {
log.Println(err)
return
}
go f(msg)
})
}
func (b *Bus) SubscribeJob(f func(msg *JobMsg)) error {
return b.safeSubscribe(b.config.jobBusKey, channelJob, func(c *emitter.Client, m emitter.Message) {
var msg JobMsg
if err := json.Unmarshal(m.Payload(), &msg); err != nil {
log.Println(err)
return
}
go f(&msg)
})
}
func (b *Bus) SubscribeResult(f func(msg *ResultMsg)) error {
return b.safeSubscribe(b.config.resultBusKey, channelResult, func(c *emitter.Client, m emitter.Message) {
var msg ResultMsg
if err := json.Unmarshal(m.Payload(), &msg); err != nil {
log.Println(err)
return
}
go f(&msg)
})
}
func (b *Bus) safeSubscribe(key, channel string, handler func(c *emitter.Client, m emitter.Message)) error {
defer func() {
if r := recover(); r != nil {

42
bus/databaseupdate.go Normal file
View File

@@ -0,0 +1,42 @@
package bus
import (
"encoding/json"
"log"
"github.com/arangodb/go-driver"
emitter "github.com/emitter-io/go/v2"
)
const channelDatabaseUpdate = "databaseupdate"
type DatabaseUpdateType string
const (
DatabaseEntryRead DatabaseUpdateType = "read"
DatabaseEntryCreated DatabaseUpdateType = "created"
DatabaseEntryUpdated DatabaseUpdateType = "updated"
)
type DatabaseUpdateMsg struct {
IDs []driver.DocumentID `json:"ids"`
Type DatabaseUpdateType `json:"type"`
}
func (b *Bus) PublishDatabaseUpdate(ids []driver.DocumentID, databaseUpdateType DatabaseUpdateType) error {
return b.jsonPublish(&DatabaseUpdateMsg{
IDs: ids,
Type: databaseUpdateType,
}, channelDatabaseUpdate, b.config.databaseUpdateBusKey)
}
func (b *Bus) SubscribeDatabaseUpdate(f func(msg *DatabaseUpdateMsg)) error {
return b.safeSubscribe(b.config.databaseUpdateBusKey, channelDatabaseUpdate, func(c *emitter.Client, m emitter.Message) {
var msg DatabaseUpdateMsg
if err := json.Unmarshal(m.Payload(), &msg); err != nil {
log.Println(err)
return
}
go f(&msg)
})
}

42
bus/job.go Normal file
View File

@@ -0,0 +1,42 @@
package bus
import (
"encoding/json"
"log"
emitter "github.com/emitter-io/go/v2"
"github.com/SecurityBrewery/catalyst/generated/model"
)
const channelJob = "job"
type JobMsg struct {
ID string `json:"id"`
Automation string `json:"automation"`
Origin *model.Origin `json:"origin"`
Message *model.Message `json:"message"`
}
func (b *Bus) PublishJob(id, automation string, payload interface{}, context *model.Context, origin *model.Origin) error {
return b.jsonPublish(&JobMsg{
ID: id,
Automation: automation,
Origin: origin,
Message: &model.Message{
Context: context,
Payload: payload,
},
}, channelJob, b.config.jobBusKey)
}
func (b *Bus) SubscribeJob(f func(msg *JobMsg)) error {
return b.safeSubscribe(b.config.jobBusKey, channelJob, func(c *emitter.Client, m emitter.Message) {
var msg JobMsg
if err := json.Unmarshal(m.Payload(), &msg); err != nil {
log.Println(err)
return
}
go f(&msg)
})
}

36
bus/request.go Normal file
View File

@@ -0,0 +1,36 @@
package bus
import (
"encoding/json"
"log"
"github.com/arangodb/go-driver"
emitter "github.com/emitter-io/go/v2"
)
const ChannelRequest = "request"
type RequestMsg struct {
IDs []driver.DocumentID `json:"ids"`
Function string `json:"function"`
User string `json:"user"`
}
func (b *Bus) PublishRequest(user, f string, ids []driver.DocumentID) error {
return b.jsonPublish(&RequestMsg{
User: user,
Function: f,
IDs: ids,
}, ChannelRequest, b.config.requestKey)
}
func (b *Bus) SubscribeRequest(f func(msg *RequestMsg)) error {
return b.safeSubscribe(b.config.requestKey, ChannelRequest, func(c *emitter.Client, m emitter.Message) {
msg := &RequestMsg{}
if err := json.Unmarshal(m.Payload(), msg); err != nil {
log.Println(err)
return
}
go f(msg)
})
}

33
bus/result.go Normal file
View File

@@ -0,0 +1,33 @@
package bus
import (
"encoding/json"
"log"
emitter "github.com/emitter-io/go/v2"
"github.com/SecurityBrewery/catalyst/generated/model"
)
const channelResult = "result"
type ResultMsg struct {
Automation string `json:"automation"`
Data map[string]interface{} `json:"data,omitempty"`
Target *model.Origin `json:"target"`
}
func (b *Bus) PublishResult(automation string, data map[string]interface{}, target *model.Origin) error {
return b.jsonPublish(&ResultMsg{Automation: automation, Data: data, Target: target}, channelResult, b.config.resultBusKey)
}
func (b *Bus) SubscribeResult(f func(msg *ResultMsg)) error {
return b.safeSubscribe(b.config.resultBusKey, channelResult, func(c *emitter.Client, m emitter.Message) {
msg := &ResultMsg{}
if err := json.Unmarshal(m.Payload(), msg); err != nil {
log.Println(err)
return
}
go f(msg)
})
}

61
busservice/busservice.go Normal file
View File

@@ -0,0 +1,61 @@
package busservice
import (
"context"
"log"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/time"
"github.com/SecurityBrewery/catalyst/role"
)
type busService struct {
db *database.Database
apiURL string
apiKey string
catalystBus *bus.Bus
network string
}
func New(apiURL, apikey, network string, catalystBus *bus.Bus, db *database.Database) error {
h := &busService{db: db, apiURL: apiURL, apiKey: apikey, network: network, catalystBus: catalystBus}
if err := catalystBus.SubscribeRequest(h.logRequest); err != nil {
return err
}
if err := catalystBus.SubscribeResult(h.handleResult); err != nil {
return err
}
if err := catalystBus.SubscribeJob(h.handleJob); err != nil {
return err
}
return nil
}
func busContext() context.Context {
// TODO: change roles?
bot := &model.UserResponse{ID: "bot", Roles: []string{role.Admin}}
return busdb.UserContext(context.Background(), bot)
}
func (h *busService) logRequest(msg *bus.RequestMsg) {
var logEntries []*model.LogEntry
for _, i := range msg.IDs {
logEntries = append(logEntries, &model.LogEntry{
Type: bus.ChannelRequest,
Reference: i.String(),
Creator: msg.User,
Message: msg.Function,
Created: time.Now().UTC(),
})
}
if err := h.db.LogBatchCreate(busContext(), logEntries); err != nil {
log.Println(err)
}
}

View File

@@ -1,4 +1,4 @@
package automation
package busservice
import (
"archive/tar"
@@ -17,7 +17,7 @@ import (
"github.com/SecurityBrewery/catalyst/database"
)
func createContainer(ctx context.Context, image, script, data string) (string, string, error) {
func createContainer(ctx context.Context, image, script, data, network string) (string, string, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return "", "", err
@@ -29,10 +29,16 @@ func createContainer(ctx context.Context, image, script, data string) (string, s
}
config := &container.Config{
Image: image, Cmd: []string{"/script", data}, WorkingDir: "/home",
AttachStderr: true, AttachStdout: true,
Image: image,
Cmd: []string{"/script", data},
WorkingDir: "/home",
AttachStderr: true,
AttachStdout: true,
}
resp, err := cli.ContainerCreate(ctx, config, nil, nil, "")
hostConfig := &container.HostConfig{
NetworkMode: container.NetworkMode(network),
}
resp, err := cli.ContainerCreate(ctx, config, hostConfig, nil, "")
if err != nil {
return "", logs, err
}

111
busservice/job.go Normal file
View File

@@ -0,0 +1,111 @@
package busservice
import (
"encoding/json"
"fmt"
"log"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func (h *busService) handleJob(automationMsg *bus.JobMsg) {
ctx := busContext()
job, err := h.db.JobCreate(ctx, automationMsg.ID, &model.JobForm{
Automation: automationMsg.Automation,
Payload: automationMsg.Message.Payload,
Origin: automationMsg.Origin,
})
if err != nil {
log.Println(err)
return
}
automation, err := h.db.AutomationGet(ctx, automationMsg.Automation)
if err != nil {
log.Println(err)
return
}
if automation.Script == "" {
log.Println("automation is empty")
return
}
if automationMsg.Message.Secrets == nil {
automationMsg.Message.Secrets = map[string]string{}
}
automationMsg.Message.Secrets["catalyst_apikey"] = h.apiKey
automationMsg.Message.Secrets["catalyst_apiurl"] = h.apiURL
scriptMessage, _ := json.Marshal(automationMsg.Message)
containerID, logs, err := createContainer(ctx, automation.Image, automation.Script, string(scriptMessage), h.network)
if err != nil {
log.Println(err)
return
}
if _, err := h.db.JobUpdate(ctx, automationMsg.ID, &model.JobUpdate{
Container: &containerID,
Running: true,
Output: job.Output,
Log: &logs,
Status: job.Status,
}); err != nil {
log.Println(err)
return
}
var result map[string]interface{}
stdout, _, err := runDocker(ctx, automationMsg.ID, containerID, h.db)
if err != nil {
result = map[string]interface{}{"error": fmt.Sprintf("error running script %s %s", err, string(stdout))}
} else {
var data map[string]interface{}
if err := json.Unmarshal(stdout, &data); err != nil {
result = map[string]interface{}{"error": string(stdout)}
} else {
result = data
}
}
if err := h.catalystBus.PublishResult(automationMsg.Automation, result, automationMsg.Origin); err != nil {
log.Println(err)
}
if err := h.db.JobComplete(ctx, automationMsg.ID, result); err != nil {
log.Println(err)
return
}
}
/*
func getAutomation(automationID string, config *Config) (*model.AutomationResponse, error) {
req, err := http.NewRequest(http.MethodGet, config.CatalystAPIUrl+"/automations/"+automationID, nil)
if err != nil {
return nil, err
}
req.Header.Set("PRIVATE-TOKEN", config.CatalystAPIKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var automation model.AutomationResponse
if err := json.Unmarshal(b, &automation); err != nil {
return nil, err
}
return &automation, nil
}
*/

35
busservice/result.go Normal file
View File

@@ -0,0 +1,35 @@
package busservice
import (
"log"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func (h *busService) handleResult(resultMsg *bus.ResultMsg) {
if resultMsg.Target != nil {
ctx := busContext()
switch {
case resultMsg.Target.TaskOrigin != nil:
if _, err := h.db.TaskComplete(
ctx,
resultMsg.Target.TaskOrigin.TicketId,
resultMsg.Target.TaskOrigin.PlaybookId,
resultMsg.Target.TaskOrigin.TaskId,
resultMsg.Data,
); err != nil {
log.Println(err)
}
case resultMsg.Target.ArtifactOrigin != nil:
enrichment := &model.EnrichmentForm{
Data: resultMsg.Data,
Name: resultMsg.Automation,
}
_, err := h.db.EnrichArtifact(ctx, resultMsg.Target.ArtifactOrigin.TicketId, resultMsg.Target.ArtifactOrigin.Artifact, enrichment)
if err != nil {
log.Println(err)
}
}
}
}

View File

@@ -3,18 +3,15 @@ package main
import (
"context"
"log"
"net/http/httputil"
"net/url"
"net/http"
"github.com/arangodb/go-driver"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst"
"github.com/SecurityBrewery/catalyst/cmd"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/hooks"
"github.com/SecurityBrewery/catalyst/role"
"github.com/SecurityBrewery/catalyst/test"
@@ -36,30 +33,20 @@ func main() {
log.Fatal(err)
}
demoUser := &models.UserResponse{ID: "demo", Roles: []string{role.Admin}}
demoUser := &model.UserResponse{ID: "demo", Roles: []string{role.Admin}}
ctx := busdb.UserContext(context.Background(), demoUser)
if err := test.SetupTestData(ctx, theCatalyst.DB); err != nil {
log.Fatal(err)
}
// proxy static requests
theCatalyst.Server.NoRoute(
sessions.Sessions(catalyst.SessionName, cookie.NewStore(config.Secret)),
middlewares := []func(next http.Handler) http.Handler{
catalyst.Authenticate(theCatalyst.DB, config.Auth),
catalyst.AuthorizeBlockedUser,
proxy,
)
catalyst.AuthorizeBlockedUser(),
}
theCatalyst.Server.With(middlewares...).NotFound(api.Proxy("http://localhost:8080"))
if err = theCatalyst.Server.RunWithSigHandler(); err != nil {
if err := http.ListenAndServe(":8000", theCatalyst.Server); err != nil {
log.Fatal(err)
}
}
func proxy(ctx *gin.Context) {
u, _ := url.Parse("http://localhost:8080")
proxy := httputil.NewSingleHostReverseProxy(u)
ctx.Request.Host = ctx.Request.URL.Host
proxy.ServeHTTP(ctx.Writer, ctx.Request)
}

View File

@@ -2,6 +2,7 @@ package main
import (
"log"
"net/http"
"github.com/SecurityBrewery/catalyst"
"github.com/SecurityBrewery/catalyst/cmd"
@@ -21,7 +22,7 @@ func main() {
log.Fatal(err)
}
if err = theCatalyst.Server.RunWithSigHandler(); err != nil {
if err := http.ListenAndServe(":8000", theCatalyst.Server); err != nil {
log.Fatal(err)
}
}

View File

@@ -1,8 +1,6 @@
package cmd
import (
"fmt"
"github.com/alecthomas/kong"
kongyaml "github.com/alecthomas/kong-yaml"
"github.com/coreos/go-oidc/v3/oidc"
@@ -11,8 +9,6 @@ import (
"github.com/SecurityBrewery/catalyst"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/role"
"github.com/SecurityBrewery/catalyst/storage"
)
@@ -21,6 +17,7 @@ type CLI struct {
Secret string `env:"SECRET" required:"" help:"A random secret value (can be created with 'openssl rand -hex 32')"`
ExternalAddress string `env:"EXTERNAL_ADDRESS" required:""`
CatalystAddress string `env:"CATALYST_ADDRESS" default:"http://catalyst:8000"`
Network string `env:"CATALYST_NETWORK" default:"catalyst"`
OIDCIssuer string `env:"OIDC_ISSUER" required:""`
OIDCClientID string `env:"OIDC_CLIENT_ID" default:"catalyst"`
@@ -31,6 +28,7 @@ type CLI struct {
OIDCClaimName string `env:"OIDC_CLAIM_NAME" default:"name" help:"name field in the OIDC claim"`
AuthBlockNew bool `env:"AUTH_BLOCK_NEW" default:"true" help:"Block newly created users"`
AuthDefaultRoles []string `env:"AUTH_DEFAULT_ROLES" help:"Default roles for new users"`
AuthAdminUsers []string `env:"AUTH_ADMIN_USERS" help:"Username of admins"`
IndexPath string `env:"INDEX_PATH" default:"index.bleve" help:"Path for the bleve index"`
@@ -45,9 +43,7 @@ type CLI struct {
EmitterIOHost string `env:"EMITTER_IO_HOST" default:"tcp://emitter:8080"`
EmitterIORKey string `env:"EMITTER_IO_KEY" required:""`
Timeformat string `env:"TIMEFORMAT" default:"yyyy-MM-dd HH:mm:ss" help:""`
ArtifactStates []map[string]string `env:"ARTIFACT_STATES"`
InitialAPIKey string `env:"INITIAL_API_KEY"`
InitialAPIKey string `env:"INITIAL_API_KEY"`
}
func ParseCatalystConfig() (*catalyst.Config, error) {
@@ -66,22 +62,10 @@ func MapConfig(cli CLI) (*catalyst.Config, error) {
roles = append(roles, role.Explodes(cli.AuthDefaultRoles)...)
roles = role.Explodes(role.Strings(roles))
artifactStates, err := toTypes(cli.ArtifactStates)
if err != nil {
return nil, err
}
if len(artifactStates) == 0 {
artifactStates = []*models.Type{
{Icon: "mdi-help-circle-outline", ID: "unknown", Name: "Unknown", Color: pointer.String(models.TypeColorInfo)},
{Icon: "mdi-skull", ID: "malicious", Name: "Malicious", Color: pointer.String(models.TypeColorError)},
{Icon: "mdi-check", ID: "clean", Name: "Clean", Color: pointer.String(models.TypeColorSuccess)},
}
}
scopes := unique(append([]string{oidc.ScopeOpenID, "profile", "email"}, cli.OIDCScopes...))
config := &catalyst.Config{
IndexPath: cli.IndexPath,
Network: cli.Network,
DB: &database.Config{Host: cli.ArangoDBHost, User: cli.ArangoDBUser, Password: cli.ArangoDBPassword},
Storage: &storage.Config{Host: cli.S3Host, User: cli.S3User, Password: cli.S3Password},
Secret: []byte(cli.Secret),
@@ -94,50 +78,14 @@ func MapConfig(cli CLI) (*catalyst.Config, error) {
OIDCClaimName: cli.OIDCClaimName,
AuthBlockNew: cli.AuthBlockNew,
AuthDefaultRoles: roles,
AuthAdminUsers: cli.AuthAdminUsers,
},
Bus: &bus.Config{Host: cli.EmitterIOHost, Key: cli.EmitterIORKey, APIUrl: cli.CatalystAddress + "/api"},
UISettings: &models.Settings{
ArtifactStates: artifactStates,
Timeformat: cli.Timeformat,
Version: catalyst.GetVersion(),
Tier: models.SettingsTierCommunity,
},
Bus: &bus.Config{Host: cli.EmitterIOHost, Key: cli.EmitterIORKey, APIUrl: cli.CatalystAddress + "/api"},
InitialAPIKey: cli.InitialAPIKey,
}
return config, nil
}
func toTypes(params []map[string]string) ([]*models.Type, error) {
var types []*models.Type
for _, param := range params {
t := &models.Type{}
icon, iconOK := param["icon"]
if iconOK {
t.Icon = icon
}
id, idOK := param["id"]
if idOK {
t.ID = id
}
name, nameOK := param["name"]
if nameOK {
t.Name = name
}
color, ok := param["color"]
if ok {
t.Color = pointer.String(color)
}
if iconOK && idOK && nameOK {
types = append(types, t)
} else {
return nil, fmt.Errorf("incomplete type: icon, id and name need to be provided (%s)", params)
}
}
return types, nil
}
func unique(l []string) []string {
keys := make(map[string]bool)
var list []string

49
cookie.go Normal file
View File

@@ -0,0 +1,49 @@
package catalyst
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
)
const (
stateSessionCookie = "state"
userSessionCookie = "user"
)
func setStateCookie(w http.ResponseWriter, state string) {
http.SetCookie(w, &http.Cookie{Name: stateSessionCookie, Value: state})
}
func stateCookie(r *http.Request) (string, error) {
stateCookie, err := r.Cookie(stateSessionCookie)
if err != nil {
return "", err
}
return stateCookie.Value, nil
}
func setClaimsCookie(w http.ResponseWriter, claims map[string]interface{}) {
b, _ := json.Marshal(claims)
http.SetCookie(w, &http.Cookie{Name: userSessionCookie, Value: base64.StdEncoding.EncodeToString(b)})
}
func claimsCookie(r *http.Request) (map[string]interface{}, bool, error) {
userCookie, err := r.Cookie(userSessionCookie)
if err != nil {
return nil, true, nil
}
b, err := base64.StdEncoding.DecodeString(userCookie.Value)
if err != nil {
return nil, false, fmt.Errorf("could not decode cookie: %w", err)
}
var claims map[string]interface{}
if err := json.Unmarshal(b, &claims); err != nil {
return nil, false, errors.New("claims not in session")
}
return claims, false, err
}

View File

@@ -3,15 +3,16 @@ package database
import (
"context"
"fmt"
"time"
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/time"
)
func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*models.Artifact, error) {
func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*model.Artifact, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -32,7 +33,7 @@ func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*mo
}
defer cursor.Close()
var doc models.Artifact
var doc model.Artifact
_, err = cursor.ReadDocument(ctx, &doc)
if err != nil {
return nil, err
@@ -41,7 +42,7 @@ func (db *Database) ArtifactGet(ctx context.Context, id int64, name string) (*mo
return &doc, nil
}
func (db *Database) ArtifactUpdate(ctx context.Context, id int64, name string, artifact *models.Artifact) (*models.TicketWithTickets, error) {
func (db *Database) ArtifactUpdate(ctx context.Context, id int64, name string, artifact *model.Artifact) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -60,16 +61,15 @@ func (db *Database) ArtifactUpdate(ctx context.Context, id int64, name string, a
"name": name,
"artifact": artifact,
}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: fmt.Sprintf("Update artifact %s", name),
})
}
func (db *Database) EnrichArtifact(ctx context.Context, id int64, name string, enrichmentForm *models.EnrichmentForm) (*models.TicketWithTickets, error) {
enrichment := models.Enrichment{time.Now().UTC(), enrichmentForm.Data, enrichmentForm.Name}
func (db *Database) EnrichArtifact(ctx context.Context, id int64, name string, enrichmentForm *model.EnrichmentForm) (*model.TicketWithTickets, error) {
enrichment := model.Enrichment{time.Now().UTC(), enrichmentForm.Data, enrichmentForm.Name}
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
@@ -78,7 +78,7 @@ func (db *Database) EnrichArtifact(ctx context.Context, id int64, name string, e
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
FOR a IN d.artifacts
FOR a IN NOT_NULL(d.artifacts, [])
FILTER a.name == @name
LET enrichments = NOT_NULL(a.enrichments, {})
LET newenrichments = MERGE(enrichments, ZIP( [@enrichmentname], [@enrichment]) )
@@ -92,10 +92,9 @@ func (db *Database) EnrichArtifact(ctx context.Context, id int64, name string, e
"enrichmentname": enrichment.Name,
"enrichment": enrichment,
}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: fmt.Sprintf("Run %s on artifact", enrichment.Name),
})
}

View File

@@ -7,11 +7,11 @@ import (
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toAutomation(doc *models.AutomationForm) interface{} {
return &models.Automation{
func toAutomation(doc *model.AutomationForm) interface{} {
return &model.Automation{
Image: doc.Image,
Script: doc.Script,
Schema: doc.Schema,
@@ -19,8 +19,8 @@ func toAutomation(doc *models.AutomationForm) interface{} {
}
}
func toAutomationResponse(id string, doc models.Automation) *models.AutomationResponse {
return &models.AutomationResponse{
func toAutomationResponse(id string, doc model.Automation) *model.AutomationResponse {
return &model.AutomationResponse{
ID: id,
Image: doc.Image,
Script: doc.Script,
@@ -29,7 +29,7 @@ func toAutomationResponse(id string, doc models.Automation) *models.AutomationRe
}
}
func (db *Database) AutomationCreate(ctx context.Context, automation *models.AutomationForm) (*models.AutomationResponse, error) {
func (db *Database) AutomationCreate(ctx context.Context, automation *model.AutomationForm) (*model.AutomationResponse, error) {
if automation == nil {
return nil, errors.New("requires automation")
}
@@ -37,7 +37,7 @@ func (db *Database) AutomationCreate(ctx context.Context, automation *models.Aut
return nil, errors.New("requires automation ID")
}
var doc models.Automation
var doc model.Automation
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.automationCollection.CreateDocument(ctx, newctx, automation.ID, toAutomation(automation))
@@ -48,8 +48,8 @@ func (db *Database) AutomationCreate(ctx context.Context, automation *models.Aut
return toAutomationResponse(meta.Key, doc), nil
}
func (db *Database) AutomationGet(ctx context.Context, id string) (*models.AutomationResponse, error) {
var doc models.Automation
func (db *Database) AutomationGet(ctx context.Context, id string) (*model.AutomationResponse, error) {
var doc model.Automation
meta, err := db.automationCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -58,8 +58,8 @@ func (db *Database) AutomationGet(ctx context.Context, id string) (*models.Autom
return toAutomationResponse(meta.Key, doc), nil
}
func (db *Database) AutomationUpdate(ctx context.Context, id string, automation *models.AutomationForm) (*models.AutomationResponse, error) {
var doc models.Automation
func (db *Database) AutomationUpdate(ctx context.Context, id string, automation *model.AutomationForm) (*model.AutomationResponse, error) {
var doc model.Automation
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.automationCollection.ReplaceDocument(ctx, id, toAutomation(automation))
@@ -75,16 +75,16 @@ func (db *Database) AutomationDelete(ctx context.Context, id string) error {
return err
}
func (db *Database) AutomationList(ctx context.Context) ([]*models.AutomationResponse, error) {
func (db *Database) AutomationList(ctx context.Context) ([]*model.AutomationResponse, error) {
query := "FOR d IN @@collection SORT d._key ASC RETURN UNSET(d, 'script')"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": AutomationCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.AutomationResponse
var docs []*model.AutomationResponse
for {
var doc models.Automation
var doc model.Automation
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break

View File

@@ -2,18 +2,15 @@ package busdb
import (
"context"
"errors"
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/generated/model"
)
type Hook interface {
PublishAction(action string, context, msg map[string]interface{}) error
PublishUpdate(col, id string) error
}
// BusDatabase
// 1. Save entry to log
// 2. Send update ticket to bus
@@ -38,34 +35,25 @@ func NewDatabase(ctx context.Context, internal driver.Database, b *bus.Bus) (*Bu
}, nil
}
type OperationType int
const (
Create OperationType = iota
Read = iota
Update = iota
)
type Operation struct {
OperationType OperationType
Ids []driver.DocumentID
Msg string
Type bus.DatabaseUpdateType
Ids []driver.DocumentID
}
var CreateOperation = &Operation{OperationType: Create}
var ReadOperation = &Operation{OperationType: Read}
var CreateOperation = &Operation{Type: bus.DatabaseEntryCreated}
var ReadOperation = &Operation{Type: bus.DatabaseEntryRead}
func (db BusDatabase) Query(ctx context.Context, query string, vars map[string]interface{}, operation *Operation) (driver.Cursor, *models.LogEntry, error) {
cur, err := db.internal.Query(ctx, query, vars)
func (db BusDatabase) Query(ctx context.Context, query string, vars map[string]interface{}, operation *Operation) (cur driver.Cursor, logs *model.LogEntry, err error) {
defer func() { err = toHTTPErr(err) }()
cur, err = db.internal.Query(ctx, query, vars)
if err != nil {
return nil, nil, err
}
var logs *models.LogEntry
switch {
case operation.OperationType == Update:
if err := db.LogAndNotify(ctx, operation.Ids, operation.Msg); err != nil {
case operation.Type == bus.DatabaseEntryCreated, operation.Type == bus.DatabaseEntryUpdated:
if err := db.bus.PublishDatabaseUpdate(operation.Ids, operation.Type); err != nil {
return nil, nil, err
}
}
@@ -73,24 +61,15 @@ func (db BusDatabase) Query(ctx context.Context, query string, vars map[string]i
return cur, logs, err
}
func (db BusDatabase) LogAndNotify(ctx context.Context, ids []driver.DocumentID, msg string) error {
var logEntries []*models.LogEntry
for _, i := range ids {
logEntries = append(logEntries, &models.LogEntry{Reference: i.String(), Message: msg})
}
func (db BusDatabase) Remove(ctx context.Context) (err error) {
defer func() { err = toHTTPErr(err) }()
if err := db.LogBatchCreate(ctx, logEntries); err != nil {
return err
}
return db.bus.PublishUpdate(ids)
}
func (db BusDatabase) Remove(ctx context.Context) error {
return db.internal.Remove(ctx)
}
func (db BusDatabase) Collection(ctx context.Context, name string) (driver.Collection, error) {
func (db BusDatabase) Collection(ctx context.Context, name string) (col driver.Collection, err error) {
defer func() { err = toHTTPErr(err) }()
return db.internal.Collection(ctx, name)
}
@@ -103,33 +82,39 @@ func NewCollection(internal driver.Collection, db *BusDatabase) *Collection {
return &Collection{internal: internal, db: db}
}
func (c Collection) CreateDocument(ctx, newctx context.Context, key string, document interface{}) (driver.DocumentMeta, error) {
meta, err := c.internal.CreateDocument(newctx, &Keyed{Key: key, Doc: document})
func (c Collection) CreateDocument(ctx, newctx context.Context, key string, document interface{}) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.CreateDocument(newctx, &Keyed{Key: key, Doc: document})
if err != nil {
return meta, err
}
err = c.db.LogAndNotify(ctx, []driver.DocumentID{meta.ID}, "Document created")
err = c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryCreated)
if err != nil {
return meta, err
}
return meta, nil
}
func (c Collection) CreateEdge(ctx, newctx context.Context, edge *driver.EdgeDocument) (driver.DocumentMeta, error) {
meta, err := c.internal.CreateDocument(newctx, edge)
func (c Collection) CreateEdge(ctx, newctx context.Context, edge *driver.EdgeDocument) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.CreateDocument(newctx, edge)
if err != nil {
return meta, err
}
err = c.db.LogAndNotify(ctx, []driver.DocumentID{meta.ID}, "Document created")
err = c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryCreated)
if err != nil {
return meta, err
}
return meta, nil
}
func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocument) (driver.DocumentMetaSlice, error) {
func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocument) (meta driver.DocumentMetaSlice, err error) {
defer func() { err = toHTTPErr(err) }()
metas, errs, err := c.internal.CreateDocuments(ctx, edges)
if err != nil {
return nil, err
@@ -143,7 +128,7 @@ func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocumen
ids = append(ids, meta.ID)
}
err = c.db.LogAndNotify(ctx, ids, "Document created")
err = c.db.bus.PublishDatabaseUpdate(ids, bus.DatabaseEntryCreated)
if err != nil {
return metas, err
}
@@ -151,32 +136,61 @@ func (c Collection) CreateEdges(ctx context.Context, edges []*driver.EdgeDocumen
return metas, nil
}
func (c Collection) DocumentExists(ctx context.Context, id string) (bool, error) {
func (c Collection) DocumentExists(ctx context.Context, id string) (exists bool, err error) {
defer func() { err = toHTTPErr(err) }()
return c.internal.DocumentExists(ctx, id)
}
func (c Collection) ReadDocument(ctx context.Context, key string, result interface{}) (driver.DocumentMeta, error) {
return c.internal.ReadDocument(ctx, key, result)
func (c Collection) ReadDocument(ctx context.Context, key string, result interface{}) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.ReadDocument(ctx, key, result)
return
}
func (c Collection) UpdateDocument(ctx context.Context, key string, update interface{}) (driver.DocumentMeta, error) {
meta, err := c.internal.UpdateDocument(ctx, key, update)
func (c Collection) UpdateDocument(ctx context.Context, key string, update interface{}) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.UpdateDocument(ctx, key, update)
if err != nil {
return meta, err
}
return meta, c.db.bus.PublishUpdate([]driver.DocumentID{meta.ID})
return meta, c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryUpdated)
}
func (c Collection) ReplaceDocument(ctx context.Context, key string, document interface{}) (driver.DocumentMeta, error) {
meta, err := c.internal.ReplaceDocument(ctx, key, document)
func (c Collection) ReplaceDocument(ctx context.Context, key string, document interface{}) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
meta, err = c.internal.ReplaceDocument(ctx, key, document)
if err != nil {
return meta, err
}
return meta, c.db.bus.PublishUpdate([]driver.DocumentID{meta.ID})
return meta, c.db.bus.PublishDatabaseUpdate([]driver.DocumentID{meta.ID}, bus.DatabaseEntryUpdated)
}
func (c Collection) RemoveDocument(ctx context.Context, formatInt string) (driver.DocumentMeta, error) {
func (c Collection) RemoveDocument(ctx context.Context, formatInt string) (meta driver.DocumentMeta, err error) {
defer func() { err = toHTTPErr(err) }()
return c.internal.RemoveDocument(ctx, formatInt)
}
func (c Collection) Truncate(ctx context.Context) (err error) {
defer func() { err = toHTTPErr(err) }()
return c.internal.Truncate(ctx)
}
func toHTTPErr(err error) error {
if err != nil {
ae := driver.ArangoError{}
if errors.As(err, &ae) {
return &api.HTTPError{Status: ae.Code, Internal: err}
}
return err
}
return nil
}

View File

@@ -2,10 +2,9 @@ package busdb
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/role"
)
@@ -14,21 +13,22 @@ const (
groupContextKey = "groups"
)
func SetContext(ctx *gin.Context, user *models.UserResponse) {
func SetContext(r *http.Request, user *model.UserResponse) *http.Request {
user.Roles = role.Strings(role.Explodes(user.Roles))
ctx.Set(userContextKey, user)
return r.WithContext(context.WithValue(r.Context(), userContextKey, user))
}
func SetGroupContext(ctx *gin.Context, groups []string) {
ctx.Set(groupContextKey, groups)
func SetGroupContext(r *http.Request, groups []string) *http.Request {
return r.WithContext(context.WithValue(r.Context(), groupContextKey, groups))
}
func UserContext(ctx context.Context, user *models.UserResponse) context.Context {
func UserContext(ctx context.Context, user *model.UserResponse) context.Context {
user.Roles = role.Strings(role.Explodes(user.Roles))
return context.WithValue(ctx, userContextKey, user)
}
func UserFromContext(ctx context.Context) (*models.UserResponse, bool) {
u, ok := ctx.Value(userContextKey).(*models.UserResponse)
func UserFromContext(ctx context.Context) (*model.UserResponse, bool) {
u, ok := ctx.Value(userContextKey).(*model.UserResponse)
return u, ok
}

View File

@@ -3,55 +3,49 @@ package busdb
import (
"context"
"errors"
"time"
"strings"
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/time"
)
const LogCollectionName = "logs"
func (db *BusDatabase) LogCreate(ctx context.Context, id, message string) (*models.LogEntry, error) {
func (db *BusDatabase) LogCreate(ctx context.Context, logType, reference, message string) (*model.LogEntry, error) {
user, ok := UserFromContext(ctx)
if !ok {
return nil, errors.New("no user in context")
}
logentry := &models.LogEntry{
Reference: id,
Created: time.Now(),
logentry := &model.LogEntry{
Type: logType,
Reference: reference,
Created: time.Now().UTC(),
Creator: user.ID,
Message: message,
}
doc := models.LogEntry{}
doc := model.LogEntry{}
_, err := db.logCollection.CreateDocument(driver.WithReturnNew(ctx, &doc), logentry)
if err != nil {
return nil, err
}
return &doc, db.bus.PublishUpdate([]driver.DocumentID{driver.DocumentID(logentry.Reference)})
return &doc, nil
}
func (db *BusDatabase) LogBatchCreate(ctx context.Context, logEntryForms []*models.LogEntry) error {
user, ok := UserFromContext(ctx)
if !ok {
return errors.New("no user in context")
}
func (db *BusDatabase) LogBatchCreate(ctx context.Context, logentries []*model.LogEntry) error {
var ids []driver.DocumentID
var logentries []*models.LogEntry
for _, logEntryForm := range logEntryForms {
logentry := &models.LogEntry{
Reference: logEntryForm.Reference,
Created: time.Now(),
Creator: user.ID,
Message: logEntryForm.Message,
for _, entry := range logentries {
if strings.HasPrefix(entry.Reference, "tickets/") {
ids = append(ids, driver.DocumentID(entry.Reference))
}
logentries = append(logentries, logentry)
ids = append(ids, driver.DocumentID(logentry.Reference))
}
if ids != nil {
go db.bus.PublishDatabaseUpdate(ids, bus.DatabaseEntryCreated)
}
_, errs, err := db.logCollection.CreateDocuments(ctx, logentries)
@@ -63,10 +57,10 @@ func (db *BusDatabase) LogBatchCreate(ctx context.Context, logEntryForms []*mode
return err
}
return db.bus.PublishUpdate(ids)
return nil
}
func (db *BusDatabase) LogList(ctx context.Context, reference string) ([]*models.LogEntry, error) {
func (db *BusDatabase) LogList(ctx context.Context, reference string) ([]*model.LogEntry, error) {
query := "FOR d IN @@collection FILTER d.reference == @reference SORT d.created DESC RETURN d"
cursor, err := db.internal.Query(ctx, query, map[string]interface{}{
"@collection": LogCollectionName,
@@ -76,9 +70,9 @@ func (db *BusDatabase) LogList(ctx context.Context, reference string) ([]*models
return nil, err
}
defer cursor.Close()
var docs []*models.LogEntry
var docs []*model.LogEntry
for {
var doc models.LogEntry
var doc model.LogEntry
_, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break

117
database/dashboard.go Normal file
View File

@@ -0,0 +1,117 @@
package database
import (
"context"
"errors"
"fmt"
"github.com/arangodb/go-driver"
"github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toDashboardResponse(key string, doc *model.Dashboard) *model.DashboardResponse {
return &model.DashboardResponse{
ID: key,
Name: doc.Name,
Widgets: doc.Widgets,
}
}
func (db *Database) DashboardCreate(ctx context.Context, dashboard *model.Dashboard) (*model.DashboardResponse, error) {
if dashboard == nil {
return nil, errors.New("requires dashboard")
}
if dashboard.Name == "" {
return nil, errors.New("requires dashboard name")
}
if err := db.parseWidgets(dashboard); err != nil {
return nil, err
}
var doc model.Dashboard
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.dashboardCollection.CreateDocument(ctx, newctx, strcase.ToKebab(dashboard.Name), dashboard)
if err != nil {
return nil, err
}
return toDashboardResponse(meta.Key, &doc), nil
}
func (db *Database) DashboardGet(ctx context.Context, id string) (*model.DashboardResponse, error) {
var doc model.Dashboard
meta, err := db.dashboardCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
}
return toDashboardResponse(meta.Key, &doc), nil
}
func (db *Database) DashboardUpdate(ctx context.Context, id string, dashboard *model.Dashboard) (*model.DashboardResponse, error) {
if err := db.parseWidgets(dashboard); err != nil {
return nil, err
}
var doc model.Dashboard
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.dashboardCollection.ReplaceDocument(ctx, id, dashboard)
if err != nil {
return nil, err
}
return toDashboardResponse(meta.Key, &doc), nil
}
func (db *Database) DashboardDelete(ctx context.Context, id string) error {
_, err := db.dashboardCollection.RemoveDocument(ctx, id)
return err
}
func (db *Database) DashboardList(ctx context.Context) ([]*model.DashboardResponse, error) {
query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": DashboardCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*model.DashboardResponse
for {
var doc model.Dashboard
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break
} else if err != nil {
return nil, err
}
docs = append(docs, toDashboardResponse(meta.Key, &doc))
}
return docs, err
}
func (db *Database) parseWidgets(dashboard *model.Dashboard) error {
for _, widget := range dashboard.Widgets {
parser := &caql.Parser{Searcher: db.Index, Prefix: "d."}
_, err := parser.Parse(widget.Aggregation)
if err != nil {
return fmt.Errorf("invalid aggregation query (%s): syntax error\n", widget.Aggregation)
}
if widget.Filter != nil {
_, err := parser.Parse(*widget.Filter)
if err != nil {
return fmt.Errorf("invalid filter query (%s): syntax error\n", *widget.Filter)
}
}
}
return nil
}

View File

@@ -25,6 +25,8 @@ const (
UserCollectionName = "users"
TicketTypeCollectionName = "tickettypes"
JobCollectionName = "jobs"
SettingsCollectionName = "settings"
DashboardCollectionName = "dashboards"
TicketArtifactsGraphName = "Graph"
RelatedTicketsCollectionName = "related"
@@ -44,9 +46,11 @@ type Database struct {
userCollection *busdb.Collection
tickettypeCollection *busdb.Collection
jobCollection *busdb.Collection
settingsCollection *busdb.Collection
dashboardCollection *busdb.Collection
relatedCollection *busdb.Collection
containsCollection *busdb.Collection
relatedCollection *busdb.Collection
// containsCollection *busdb.Collection
}
type Config struct {
@@ -66,6 +70,7 @@ func New(ctx context.Context, index *index.Index, bus *bus.Bus, hooks *hooks.Hoo
if err != nil {
return nil, err
}
client, err := driver.NewClient(driver.ClientConfig{
Connection: conn,
Authentication: driver.BasicAuthentication(config.User, config.Password),
@@ -76,58 +81,66 @@ func New(ctx context.Context, index *index.Index, bus *bus.Bus, hooks *hooks.Hoo
hooks.DatabaseAfterConnect(ctx, client, name)
db, err := setupDB(ctx, client, name)
arangoDB, err := SetupDB(ctx, client, name)
if err != nil {
return nil, fmt.Errorf("DB setup failed: %w", err)
}
if err = migrations.PerformMigrations(ctx, db); err != nil {
if err = migrations.PerformMigrations(ctx, arangoDB); err != nil {
return nil, fmt.Errorf("migrations failed: %w", err)
}
ticketCollection, err := db.Collection(ctx, TicketCollectionName)
ticketCollection, err := arangoDB.Collection(ctx, TicketCollectionName)
if err != nil {
return nil, err
}
templateCollection, err := db.Collection(ctx, TemplateCollectionName)
templateCollection, err := arangoDB.Collection(ctx, TemplateCollectionName)
if err != nil {
return nil, err
}
playbookCollection, err := db.Collection(ctx, PlaybookCollectionName)
playbookCollection, err := arangoDB.Collection(ctx, PlaybookCollectionName)
if err != nil {
return nil, err
}
relatedCollection, err := db.Collection(ctx, RelatedTicketsCollectionName)
relatedCollection, err := arangoDB.Collection(ctx, RelatedTicketsCollectionName)
if err != nil {
return nil, err
}
automationCollection, err := db.Collection(ctx, AutomationCollectionName)
automationCollection, err := arangoDB.Collection(ctx, AutomationCollectionName)
if err != nil {
return nil, err
}
userdataCollection, err := db.Collection(ctx, UserDataCollectionName)
userdataCollection, err := arangoDB.Collection(ctx, UserDataCollectionName)
if err != nil {
return nil, err
}
userCollection, err := db.Collection(ctx, UserCollectionName)
userCollection, err := arangoDB.Collection(ctx, UserCollectionName)
if err != nil {
return nil, err
}
tickettypeCollection, err := db.Collection(ctx, TicketTypeCollectionName)
tickettypeCollection, err := arangoDB.Collection(ctx, TicketTypeCollectionName)
if err != nil {
return nil, err
}
jobCollection, err := db.Collection(ctx, JobCollectionName)
jobCollection, err := arangoDB.Collection(ctx, JobCollectionName)
if err != nil {
return nil, err
}
settingsCollection, err := arangoDB.Collection(ctx, SettingsCollectionName)
if err != nil {
return nil, err
}
dashboardCollection, err := arangoDB.Collection(ctx, DashboardCollectionName)
if err != nil {
return nil, err
}
hookedDB, err := busdb.NewDatabase(ctx, db, bus)
hookedDB, err := busdb.NewDatabase(ctx, arangoDB, bus)
if err != nil {
return nil, err
}
return &Database{
db := &Database{
BusDatabase: hookedDB,
bus: bus,
Index: index,
@@ -141,10 +154,14 @@ func New(ctx context.Context, index *index.Index, bus *bus.Bus, hooks *hooks.Hoo
userCollection: busdb.NewCollection(userCollection, hookedDB),
tickettypeCollection: busdb.NewCollection(tickettypeCollection, hookedDB),
jobCollection: busdb.NewCollection(jobCollection, hookedDB),
}, nil
settingsCollection: busdb.NewCollection(settingsCollection, hookedDB),
dashboardCollection: busdb.NewCollection(dashboardCollection, hookedDB),
}
return db, nil
}
func setupDB(ctx context.Context, client driver.Client, dbName string) (driver.Database, error) {
func SetupDB(ctx context.Context, client driver.Client, dbName string) (driver.Database, error) {
databaseExists, err := client.DatabaseExists(ctx, dbName)
if err != nil {
return nil, err
@@ -175,3 +192,18 @@ func setupDB(ctx context.Context, client driver.Client, dbName string) (driver.D
return db, nil
}
func (db *Database) Truncate(ctx context.Context) {
db.templateCollection.Truncate(ctx)
db.ticketCollection.Truncate(ctx)
db.playbookCollection.Truncate(ctx)
db.automationCollection.Truncate(ctx)
db.userdataCollection.Truncate(ctx)
db.userCollection.Truncate(ctx)
db.tickettypeCollection.Truncate(ctx)
db.jobCollection.Truncate(ctx)
db.relatedCollection.Truncate(ctx)
db.settingsCollection.Truncate(ctx)
db.dashboardCollection.Truncate(ctx)
// db.containsCollection.Truncate(ctx)
}

View File

@@ -5,19 +5,18 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/arangodb/go-driver"
"github.com/docker/docker/client"
"github.com/xeipuuv/gojsonschema"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toJob(doc *models.JobForm) *models.Job {
return &models.Job{
func toJob(doc *model.JobForm) *model.Job {
return &model.Job{
Automation: doc.Automation,
Payload: doc.Payload,
Origin: doc.Origin,
@@ -26,7 +25,7 @@ func toJob(doc *models.JobForm) *models.Job {
}
}
func (db *Database) toJobResponse(ctx context.Context, key string, doc *models.Job, update bool) (*models.JobResponse, error) {
func (db *Database) toJobResponse(ctx context.Context, key string, doc *model.Job, update bool) (*model.JobResponse, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
@@ -38,20 +37,24 @@ func (db *Database) toJobResponse(ctx context.Context, key string, doc *models.J
if doc.Running {
inspect, err := cli.ContainerInspect(ctx, key)
if err != nil || inspect.State == nil {
doc.Running = false
if update {
db.JobUpdate(ctx, key, doc)
db.JobUpdate(ctx, key, &model.JobUpdate{
Status: doc.Status,
Running: false,
})
}
} else if doc.Status != inspect.State.Status {
status = inspect.State.Status
doc.Status = inspect.State.Status
if update {
db.JobUpdate(ctx, key, doc)
db.JobUpdate(ctx, key, &model.JobUpdate{
Status: status,
Running: doc.Running,
})
}
}
}
return &models.JobResponse{
return &model.JobResponse{
Automation: doc.Automation,
ID: key,
Log: doc.Log,
@@ -63,33 +66,15 @@ func (db *Database) toJobResponse(ctx context.Context, key string, doc *models.J
}, nil
}
func (db *Database) JobCreate(ctx context.Context, id string, job *models.JobForm) (*models.JobResponse, error) {
func (db *Database) JobCreate(ctx context.Context, id string, job *model.JobForm) (*model.JobResponse, error) {
if job == nil {
return nil, errors.New("requires job")
}
var doc models.Job
var doc model.Job
newctx := driver.WithReturnNew(ctx, &doc)
/* Start validation */
j := toJob(job)
b, _ := json.Marshal(j)
r, err := models.JobSchema.Validate(gojsonschema.NewBytesLoader(b))
if err != nil {
return nil, err
}
if !r.Valid() {
var errs []string
for _, e := range r.Errors() {
errs = append(errs, e.String())
}
return nil, errors.New(strings.Join(errs, ", "))
}
/* End validation */
meta, err := db.jobCollection.CreateDocument(ctx, newctx, id, j)
meta, err := db.jobCollection.CreateDocument(ctx, newctx, id, toJob(job))
if err != nil {
return nil, err
}
@@ -97,8 +82,8 @@ func (db *Database) JobCreate(ctx context.Context, id string, job *models.JobFor
return db.toJobResponse(ctx, meta.Key, &doc, true)
}
func (db *Database) JobGet(ctx context.Context, id string) (*models.JobResponse, error) {
var doc models.Job
func (db *Database) JobGet(ctx context.Context, id string) (*model.JobResponse, error) {
var doc model.Job
meta, err := db.jobCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -107,28 +92,11 @@ func (db *Database) JobGet(ctx context.Context, id string) (*models.JobResponse,
return db.toJobResponse(ctx, meta.Key, &doc, true)
}
func (db *Database) JobUpdate(ctx context.Context, id string, job *models.Job) (*models.JobResponse, error) {
var doc models.Job
func (db *Database) JobUpdate(ctx context.Context, id string, job *model.JobUpdate) (*model.JobResponse, error) {
var doc model.Job
ctx = driver.WithReturnNew(ctx, &doc)
/* Start validation */
b, _ := json.Marshal(job)
r, err := models.JobSchema.Validate(gojsonschema.NewBytesLoader(b))
if err != nil {
return nil, err
}
if !r.Valid() {
var errs []string
for _, e := range r.Errors() {
errs = append(errs, e.String())
}
return nil, errors.New(strings.Join(errs, ", "))
}
/* End validation */
meta, err := db.jobCollection.ReplaceDocument(ctx, id, job)
meta, err := db.jobCollection.UpdateDocument(ctx, id, job)
if err != nil {
return nil, err
}
@@ -144,11 +112,10 @@ func (db *Database) JobLogAppend(ctx context.Context, id string, logLine string)
"ID": id,
"logline": logLine,
}, &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%s", JobCollectionName, id)),
},
Msg: fmt.Sprintf("Append logline"),
})
if err != nil {
return err
@@ -166,11 +133,10 @@ func (db *Database) JobComplete(ctx context.Context, id string, out interface{})
"ID": id,
"out": out,
}, &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%s", JobCollectionName, id)),
},
Msg: fmt.Sprintf("Set output"),
})
if err != nil {
return err
@@ -185,16 +151,16 @@ func (db *Database) JobDelete(ctx context.Context, id string) error {
return err
}
func (db *Database) JobList(ctx context.Context) ([]*models.JobResponse, error) {
func (db *Database) JobList(ctx context.Context) ([]*model.JobResponse, error) {
query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": JobCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.JobResponse
var docs []*model.JobResponse
for {
var doc models.Job
var doc model.Job
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break
@@ -213,7 +179,7 @@ func (db *Database) JobList(ctx context.Context) ([]*models.JobResponse, error)
return docs, err
}
func publishJobMapping(id, automation string, contextStructs *models.Context, origin *models.Origin, payloadMapping map[string]string, db *Database) error {
func publishJobMapping(id, automation string, contextStructs *model.Context, origin *model.Origin, payloadMapping map[string]string, db *Database) error {
msg, err := generatePayload(payloadMapping, contextStructs)
if err != nil {
return fmt.Errorf("message generation failed: %w", err)
@@ -222,11 +188,11 @@ func publishJobMapping(id, automation string, contextStructs *models.Context, or
return publishJob(id, automation, contextStructs, origin, msg, db)
}
func publishJob(id, automation string, contextStructs *models.Context, origin *models.Origin, payload map[string]interface{}, db *Database) error {
func publishJob(id, automation string, contextStructs *model.Context, origin *model.Origin, payload map[string]interface{}, db *Database) error {
return db.bus.PublishJob(id, automation, payload, contextStructs, origin)
}
func generatePayload(msgMapping map[string]string, contextStructs *models.Context) (map[string]interface{}, error) {
func generatePayload(msgMapping map[string]string, contextStructs *model.Context) (map[string]interface{}, error) {
contextJson, err := json.Marshal(contextStructs)
if err != nil {
return nil, err

View File

@@ -1,630 +0,0 @@
#!/usr/bin/env python
import subprocess
import sys
import json
from datetime import datetime
import io
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "thehive4py", "requests", "minio"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
defaultschema = {
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/object1618746510.json",
"title": "Default",
"type": "object",
"required": [
"severity",
"description",
"summary",
"tlp",
"pap"
],
"properties": {
"severity": {
"$id": "#root/severity",
"title": "Severity",
"type": "string",
"default": "Medium",
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "Unknown",
"title": "Unknown",
"icon": "mdi-help"
},
{
"const": "Low",
"title": "Low",
"icon": "mdi-chevron-up"
},
{
"const": "Medium",
"title": "Medium",
"icon": "mdi-chevron-double-up"
},
{
"const": "High",
"title": "High",
"icon": "mdi-chevron-triple-up"
},
{
"const": "Very High",
"title": "Very High",
"icon": "mdi-exclamation"
}
]
},
"flag": {
"title": "Flag",
"type": "boolean",
"x-cols": 6,
},
"tlp": {
"$id": "#root/tlp",
"title": "TLP",
"type": "string",
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "White",
"title": "White",
"icon": "mdi-alpha-w"
},
{
"const": "Green",
"title": "Green",
"icon": "mdi-alpha-g"
},
{
"const": "Amber",
"title": "Amber",
"icon": "mdi-alpha-a"
},
{
"const": "Red",
"title": "Red",
"icon": "mdi-alpha-r"
}
]
},
"pap": {
"$id": "#root/pap",
"title": "PAP",
"type": "string",
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "White",
"title": "White",
"icon": "mdi-alpha-w"
},
{
"const": "Green",
"title": "Green",
"icon": "mdi-alpha-g"
},
{
"const": "Amber",
"title": "Amber",
"icon": "mdi-alpha-a"
},
{
"const": "Red",
"title": "Red",
"icon": "mdi-alpha-r"
}
]
},
"tags": {
"$id": "#root/tags",
"title": "Tags",
"type": "array",
"items": {
"type": "string"
}
},
"description": {
"$id": "#root/description",
"title": "Description",
"type": "string",
"x-display": "textarea",
"x-class": "pr-2"
},
"resolutionStatus": {
"$id": "#root/resolutionStatus",
"title": "Resolution Status",
"type": "string",
"x-cols": 6,
"x-class": "pr-2",
},
"endDate": {
"$id": "#root/endDate",
"title": "End Data",
"type": "string",
"format": "date-time",
"x-cols": 6,
"x-class": "pr-2",
},
"summary": {
"$id": "#root/summary",
"title": "Summary",
"type": "string",
"x-display": "textarea",
"x-class": "pr-2"
}
}
}
defaultalertschema = {
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/object1618746510.json",
"title": "Default",
"type": "object",
"required": [
"severity",
"description",
"summary",
"tlp",
"pap"
],
"properties": {
"severity": {
"$id": "#root/severity",
"title": "Severity",
"type": "string",
"default": "Medium",
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "Unknown",
"title": "Unknown",
"icon": "mdi-help"
},
{
"const": "Low",
"title": "Low",
"icon": "mdi-chevron-up"
},
{
"const": "Medium",
"title": "Medium",
"icon": "mdi-chevron-double-up"
},
{
"const": "High",
"title": "High",
"icon": "mdi-chevron-triple-up"
},
{
"const": "Very High",
"title": "Very High",
"icon": "mdi-exclamation"
}
]
},
"tlp": {
"$id": "#root/tlp",
"title": "TLP",
"type": "string",
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "White",
"title": "White",
"icon": "mdi-alpha-w"
},
{
"const": "Green",
"title": "Green",
"icon": "mdi-alpha-g"
},
{
"const": "Amber",
"title": "Amber",
"icon": "mdi-alpha-a"
},
{
"const": "Red",
"title": "Red",
"icon": "mdi-alpha-r"
}
]
},
"source": {
"$id": "#root/source",
"title": "Source",
"type": "string",
"x-cols": 4,
"x-class": "pr-2",
},
"sourceRef": {
"$id": "#root/sourceRef",
"title": "Source Ref",
"type": "string",
"x-cols": 4,
"x-class": "pr-2",
},
"type": {
"$id": "#root/type",
"title": "Type",
"type": "string",
"x-cols": 4,
"x-class": "pr-2",
},
"description": {
"$id": "#root/description",
"title": "Description",
"type": "string",
"x-display": "textarea",
"x-class": "pr-2"
}
}
}
class schema:
def __init__(self):
self.schema = defaultschema
def add_string(self, title):
self.schema["properties"][title] = { "type": "string", "x-cols": 6, "x-class": "pr-2" }
def add_boolean(self, title):
self.schema["properties"][title] = { "type": "boolean", "x-cols": 6, "x-class": "pr-2" }
def add_date(self, title):
self.schema["properties"][title] = { "type": "string", "format": "date-time", "x-cols": 6, "x-class": "pr-2" }
def add_integer(self, title):
self.schema["properties"][title] = { "type": "integer", "x-cols": 6, "x-class": "pr-2" }
def add_float(self, title):
self.schema["properties"][title] = { "type": "number", "x-cols": 6, "x-class": "pr-2" }
class alertschema:
def __init__(self):
self.schema = defaultalertschema
def maptime(hivetime):
if hivetime is None:
return None
return datetime.fromtimestamp(hivetime/1000).isoformat() + "Z"
def mapstatus(hivestatus):
if hivestatus == "Open" or hivestatus == "New":
return "open"
return "closed"
def maptlp(hivetlp):
if hivetlp == 0:
return "White"
if hivetlp == 1:
return "Green"
if hivetlp == 2:
return "Amber"
if hivetlp == 3:
return "Red"
return "White"
def mapseverity(hiveseverity):
if hiveseverity == 1:
return "Low"
if hiveseverity == 2:
return "Medium"
if hiveseverity == 3:
return "High"
if hiveseverity == 4:
return "Very High"
return "Unknown"
# {
# "_id": "~16416",
# "id": "~16416",
# "createdBy": "jonas@thehive.local",
# "updatedBy": "jonas@thehive.local",
# "createdAt": 1638704013583,
# "updatedAt": 1638704061151,
# "_type": "case",
# "caseId": 1,
# "title": "My Test 1",
# "description": "My Testcase",
# "severity": 2,
# "startDate": 1638703980000,
# "endDate": null,
# "impactStatus": null,
# "resolutionStatus": null,
# "tags": [],
# "flag": false,
# "tlp": 2,
# "pap": 2,
# "status": "Open",
# "summary": null,
# "owner": "jonas@thehive.local",
# "customFields": {},
# "stats": {},
# "permissions": [ "manageShare", "manageAnalyse", "manageTask", "manageCaseTemplate", "manageCase", "manageUser", "manageProcedure", "managePage", "manageObservable", "manageTag", "manageConfig", "manageAlert", "accessTheHiveFS", "manageAction" ]
# }
def mapcase(hivecase, url, keep_ids):
s = schema()
details = {}
for name, data in hivecase["customFields"].items():
if "string" in data and data["string"] is not None:
s.add_string(name)
details[name] = data["string"]
if "boolean" in data and data["boolean"] is not None:
s.add_boolean(name)
details[name] = data["boolean"]
if "date" in data and data["date"] is not None:
s.add_date(name)
details[name] = maptime(data["date"])
if "integer" in data and data["integer"] is not None:
s.add_integer(name)
details[name] = data["integer"]
if "float" in data and data["float"] is not None:
s.add_float(name)
details[name] = data["float"]
case = {}
if keep_ids:
case["id"] = hivecase["caseId"]
return {
"name": hivecase["title"],
"type": "incident",
"status": mapstatus(hivecase["status"]),
"owner": hivecase["owner"],
# "write": hivecase["write"],
# "read": hivecase["read"],
"schema": json.dumps(s.schema),
"details": {
"tlp": maptlp(hivecase["tlp"]),
"pap": maptlp(hivecase["pap"]),
"severity": mapseverity(hivecase["severity"]),
"description": hivecase["description"],
"summary": hivecase["summary"],
"tags": hivecase["tags"],
"endDate": maptime(hivecase["endDate"]),
"resolutionStatus": hivecase["resolutionStatus"],
"flag": hivecase["flag"],
} | details,
"references": [
{ "name": "TheHive #%d" % hivecase["caseId"], "href": "%s/index.html#!/case/~%s/details" % (url, hivecase["id"]) }
],
#
# "playbooks": hivecase["playbooks"],
#
"files": [],
"comments": [],
# creator, created, message
#
"artifacts": [],
# name, type, status, enrichment
# name, data
"created": maptime(hivecase["createdAt"]),
"modified": maptime(hivecase["updatedAt"]),
} | case
# {
# "_id": "ce2c00f17132359cb3c50dfbb1901810",
# "_type": "alert",
# "artifacts": [],
# "createdAt": 1495012062014,
# "createdBy": "myuser",
# "date": 1495012062016,
# "description": "N/A",
# "follow": true,
# "id": "ce2c00f17132359cb3c50dfbb1901810",
# "lastSyncDate": 1495012062016,
# "severity": 2,
# "source": "instance1",
# "sourceRef": "alert-ref",
# "status": "New",
# "title": "New Alert",
# "tlp": 2,
# "type": "external",
# "user": "myuser"
# }
def mapalert(hivealert, url):
s = alertschema()
details = {}
return {
"name": hivealert["title"],
"type": "alert",
"status": mapstatus(hivealert["status"]),
"owner": hivealert["user"],
"schema": json.dumps(s.schema),
"details": {
"tlp": maptlp(hivealert["tlp"]),
"severity": mapseverity(hivealert["severity"]),
"description": hivealert["description"],
"source": hivealert["source"],
"sourceRef": hivealert["sourceRef"],
"type": hivealert["type"],
} | details,
"references": [
{ "name": "TheHive Alerts", "href": "%s/index.html#!/alert/list" % url }
],
"files": [],
"comments": [],
"artifacts": [],
"created": maptime(hivealert["createdAt"]),
"modified": maptime(hivealert["lastSyncDate"]),
}
# {
# "_id": "~41152",
# "id": "~41152",
# "createdBy": "jonas@thehive.local",
# "createdAt": 1638723814523,
# "_type": "case_artifact",
# "dataType": "ip",
# "data": "2.2.2.2",
# "startDate": 1638723814523,
# "tlp": 2,
# "tags": [],
# "ioc": false,
# "sighted": false,
# "message": ".",
# "reports": {},
# "stats": {},
# "ignoreSimilarity": false
# }
def mapobservable(hiveobservable):
status = "unknown"
if hiveobservable["ioc"]:
status = "malicious"
return {
"name": hiveobservable["data"],
"type": hiveobservable["dataType"],
"status": status,
}
# {
# "id": "~12296",
# "_id": "~12296",
# "createdBy": "jonas@thehive.local",
# "createdAt": 1638704029800,
# "_type": "case_task",
# "title": "Start",
# "group": "MyTaskGroup1",
# "owner": "jonas@thehive.local",
# "status": "InProgress",
# "flag": false,
# "startDate": 1638704115667,
# "order": 0
# }
# {
# "_id": "~24656",
# "id": "~24656",
# "createdBy": "jonas@thehive.local",
# "createdAt": 1638729992590,
# "_type": "case_task_log",
# "message": "asd",
# "startDate": 1638729992590,
# "attachment": {
# "name": "Chemistry Vector.eps",
# "hashes": [
# "adf2d4cd72f4141fe7f8eb4af035596415a29c048d3039be6449008f291258e9",
# "180f66a6d22b1f09ed198afd814f701e42440e7c",
# "b28ae347371df003b76cbb8c6199c97e"
# ],
# "size": 3421842,
# "contentType": "application/postscript",
# "id": "adf2d4cd72f4141fe7f8eb4af035596415a29c048d3039be6449008f291258e9"
# },
# "status": "Ok",
# "owner": "jonas@thehive.local"
# }
def maptasklog(hivetask, hivetasklog):
message = "**" + hivetask["group"] + ": " + hivetask["title"] + "** (" + hivetask["status"] + ")\n\n"
message += hivetasklog["message"]
if 'attachment' in hivetasklog:
message += "\n\n*Attachment*: " + hivetasklog['attachment']["name"]
return {
"creator": hivetasklog["createdBy"],
"created": maptime(hivetasklog["createdAt"]),
"message": message,
}
def run(msg):
skip_files = msg["payload"]["skip_files"]
keep_ids = msg["payload"]["keep_ids"]
from thehive4py.api import TheHiveApi
import requests
from minio import Minio
headers = {"PRIVATE-TOKEN": msg["secrets"]["catalyst_apikey"]}
# minioclient = Minio("try.catalyst-soar.com:9000", access_key="minio", secret_key="password")
if not skip_files:
minioclient = Minio(
msg["secrets"]["minio_host"],
access_key=msg["secrets"]["minio_access_key"],
secret_key=msg["secrets"]["minio_secret_key"])
# url = "http://localhost:9000"
url = msg["payload"]["thehiveurl"]
# api = TheHiveApi(url, "dtUCnzY4h291GIFHJKW/Z2I2SgjTRQqo")
api = TheHiveApi(url, msg["payload"]["thehivekey"])
print("find alerts", file=sys.stderr)
alerts = []
resp = api.find_alerts(query={}, sort=['-createdAt'], range='all')
resp.raise_for_status()
for alert in resp.json():
alerts.append(mapalert(alert, url))
if alerts:
print("create %s alerts" % len(alerts), file=sys.stderr)
response = requests.post(msg["secrets"]["catalyst_apiurl"] + "/tickets/batch", json=alerts, headers=headers)
response.raise_for_status()
print("find incidents", file=sys.stderr)
incidents = []
resp = api.find_cases(query={}, sort=['-createdAt'], range='all')
resp.raise_for_status()
for case in resp.json():
incident = mapcase(case, url, keep_ids)
for observable in api.get_case_observables(case["id"]).json():
incident["artifacts"].append(mapobservable(observable))
for task in api.get_case_tasks(case["id"]).json():
for log in api.get_task_logs(task["id"]).json():
incident["comments"].append(maptasklog(task, log))
if 'attachment' in log and not skip_files:
incident["files"].append({ "key": log['attachment']["id"], "name": log['attachment']["name"] })
bucket_name = "catalyst-%d" % incident["id"]
if not minioclient.bucket_exists(bucket_name):
minioclient.make_bucket(bucket_name)
response = api.download_attachment(log["attachment"]["id"])
data = io.BytesIO(response.content)
minioclient.put_object(bucket_name, log["attachment"]["id"], data, length=-1, part_size=10*1024*1024)
incidents.append(incident)
if incidents:
if keep_ids:
print("delete incidents", file=sys.stderr)
for incident in incidents:
requests.delete(msg["secrets"]["catalyst_apiurl"] + "/tickets/%d" % incident["id"], headers=headers)
print("create %d incidents" % len(incidents), file=sys.stderr)
response = requests.post(msg["secrets"]["catalyst_apiurl"] + "/tickets/batch", json=incidents, headers=headers)
response.raise_for_status()
return {"done": True}
print(json.dumps(run(json.loads(sys.argv[1]))))

View File

@@ -11,9 +11,6 @@ var SHA1HashAutomation string
//go:embed automations/vt.hash.py
var VTHashAutomation string
//go:embed automations/thehive.py
var TheHiveAutomation string
//go:embed automations/comment.py
var CommentAutomation string

View File

@@ -7,8 +7,8 @@ import (
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/pointer"
)
const MigrationCollection string = "migrations"
@@ -32,25 +32,32 @@ func generateMigrations() ([]Migration, error) {
&createGraph{ID: "create-ticket-graph", Name: "Graph", EdgeDefinitions: []driver.EdgeDefinition{{Collection: "related", From: []string{"tickets"}, To: []string{"tickets"}}}},
&createDocument{ID: "create-template-default", Collection: "templates", Document: &busdb.Keyed{Key: "default", Doc: models.TicketTemplate{Schema: DefaultTemplateSchema, Name: "Default"}}},
&createDocument{ID: "create-automation-vt.hash", Collection: "automations", Document: &busdb.Keyed{Key: "vt.hash", Doc: models.Automation{Image: "docker.io/python:3", Script: VTHashAutomation}}},
&createDocument{ID: "create-automation-comment", Collection: "automations", Document: &busdb.Keyed{Key: "comment", Doc: models.Automation{Image: "docker.io/python:3", Script: CommentAutomation}}},
&createDocument{ID: "create-automation-thehive", Collection: "automations", Document: &busdb.Keyed{Key: "thehive", Doc: models.Automation{Image: "docker.io/python:3", Script: TheHiveAutomation}}},
&createDocument{ID: "create-automation-hash.sha1", Collection: "automations", Document: &busdb.Keyed{Key: "hash.sha1", Doc: models.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation}}},
&createDocument{ID: "create-playbook-malware", Collection: "playbooks", Document: &busdb.Keyed{Key: "malware", Doc: models.PlaybookTemplate{Name: "Malware", Yaml: MalwarePlaybook}}},
&createDocument{ID: "create-playbook-phishing", Collection: "playbooks", Document: &busdb.Keyed{Key: "phishing", Doc: models.PlaybookTemplate{Name: "Phishing", Yaml: PhishingPlaybook}}},
&createDocument{ID: "create-tickettype-alert", Collection: "tickettypes", Document: &busdb.Keyed{Key: "alert", Doc: models.TicketType{Name: "Alerts", Icon: "mdi-alert", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-incident", Collection: "tickettypes", Document: &busdb.Keyed{Key: "incident", Doc: models.TicketType{Name: "Incidents", Icon: "mdi-radioactive", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-investigation", Collection: "tickettypes", Document: &busdb.Keyed{Key: "investigation", Doc: models.TicketType{Name: "Forensic Investigations", Icon: "mdi-fingerprint", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-hunt", Collection: "tickettypes", Document: &busdb.Keyed{Key: "hunt", Doc: models.TicketType{Name: "Threat Hunting", Icon: "mdi-target", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-template-default", Collection: "templates", Document: &busdb.Keyed{Key: "default", Doc: model.TicketTemplate{Schema: DefaultTemplateSchema, Name: "Default"}}},
&createDocument{ID: "create-automation-vt.hash", Collection: "automations", Document: &busdb.Keyed{Key: "vt.hash", Doc: model.Automation{Image: "docker.io/python:3", Script: VTHashAutomation}}},
&createDocument{ID: "create-automation-comment", Collection: "automations", Document: &busdb.Keyed{Key: "comment", Doc: model.Automation{Image: "docker.io/python:3", Script: CommentAutomation}}},
&createDocument{ID: "create-automation-hash.sha1", Collection: "automations", Document: &busdb.Keyed{Key: "hash.sha1", Doc: model.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation}}},
&createDocument{ID: "create-playbook-malware", Collection: "playbooks", Document: &busdb.Keyed{Key: "malware", Doc: model.PlaybookTemplate{Name: "Malware", Yaml: MalwarePlaybook}}},
&createDocument{ID: "create-playbook-phishing", Collection: "playbooks", Document: &busdb.Keyed{Key: "phishing", Doc: model.PlaybookTemplate{Name: "Phishing", Yaml: PhishingPlaybook}}},
&createDocument{ID: "create-tickettype-alert", Collection: "tickettypes", Document: &busdb.Keyed{Key: "alert", Doc: model.TicketType{Name: "Alerts", Icon: "mdi-alert", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-incident", Collection: "tickettypes", Document: &busdb.Keyed{Key: "incident", Doc: model.TicketType{Name: "Incidents", Icon: "mdi-radioactive", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-investigation", Collection: "tickettypes", Document: &busdb.Keyed{Key: "investigation", Doc: model.TicketType{Name: "Forensic Investigations", Icon: "mdi-fingerprint", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&createDocument{ID: "create-tickettype-hunt", Collection: "tickettypes", Document: &busdb.Keyed{Key: "hunt", Doc: model.TicketType{Name: "Threat Hunting", Icon: "mdi-target", DefaultTemplate: "default", DefaultPlaybooks: []string{}, DefaultGroups: nil}}},
&updateSchema{ID: "update-automation-collection-1", Name: "automations", DataType: "automation", Schema: `{"properties":{"image":{"type":"string"},"script":{"type":"string"}},"required":["image","script"],"type":"object"}`},
&updateDocument{ID: "update-automation-vt.hash-1", Collection: "automations", Key: "vt.hash", Document: models.Automation{Image: "docker.io/python:3", Script: VTHashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}},
&updateDocument{ID: "update-automation-comment-1", Collection: "automations", Key: "comment", Document: models.Automation{Image: "docker.io/python:3", Script: CommentAutomation, Type: []string{"playbook"}}},
&updateDocument{ID: "update-automation-thehive-1", Collection: "automations", Key: "thehive", Document: models.Automation{Image: "docker.io/python:3", Script: TheHiveAutomation, Schema: pointer.String(`{"title":"TheHive credentials","type":"object","properties":{"thehiveurl":{"type":"string","title":"TheHive URL (e.g. 'https://thehive.example.org')"},"thehivekey":{"type":"string","title":"TheHive API Key"},"skip_files":{"type":"boolean", "default": true, "title":"Skip Files (much faster)"},"keep_ids":{"type":"boolean", "default": true, "title":"Keep IDs and overwrite existing IDs"}},"required":["thehiveurl", "thehivekey", "skip_files", "keep_ids"]}`), Type: []string{"global"}}},
&updateDocument{ID: "update-automation-hash.sha1-1", Collection: "automations", Key: "hash.sha1", Document: models.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}},
&updateDocument{ID: "update-automation-vt.hash-1", Collection: "automations", Key: "vt.hash", Document: model.Automation{Image: "docker.io/python:3", Script: VTHashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}},
&updateDocument{ID: "update-automation-comment-1", Collection: "automations", Key: "comment", Document: model.Automation{Image: "docker.io/python:3", Script: CommentAutomation, Type: []string{"playbook"}}},
&updateDocument{ID: "update-automation-hash.sha1-1", Collection: "automations", Key: "hash.sha1", Document: model.Automation{Image: "docker.io/python:3", Script: SHA1HashAutomation, Schema: pointer.String(`{"title":"Input","type":"object","properties":{"default":{"type":"string","title":"Value"}},"required":["default"]}`), Type: []string{"global", "artifact", "playbook"}}},
&createCollection{ID: "create-job-collection", Name: "jobs", DataType: "job", Schema: `{"properties":{"automation":{"type":"string"},"log":{"type":"string"},"payload":{},"origin":{"properties":{"artifact_origin":{"properties":{"artifact":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["artifact","ticket_id"],"type":"object"},"task_origin":{"properties":{"playbook_id":{"type":"string"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["playbook_id","task_id","ticket_id"],"type":"object"}},"type":"object"},"output":{"properties":{},"type":"object"},"running":{"type":"boolean"},"status":{"type":"string"}},"required":["automation","running","status"],"type":"object"}`},
&createDocument{ID: "create-playbook-simple", Collection: "playbooks", Document: &busdb.Keyed{Key: "simple", Doc: model.PlaybookTemplate{Name: "Simple", Yaml: SimplePlaybook}}},
&createCollection{ID: "create-settings-collection", Name: "settings", DataType: "settings", Schema: `{"type":"object","properties":{"artifactStates":{"title":"Artifact States","items":{"type":"object","properties":{"color":{"title":"Color","type":"string","enum":["error","info","success","warning"]},"icon":{"title":"Icon (https://materialdesignicons.com)","type":"string"},"id":{"title":"ID","type":"string"},"name":{"title":"Name","type":"string"}},"required":["id","name","icon"]},"type":"array"},"artifactKinds":{"title":"Artifact Kinds","items":{"type":"object","properties":{"color":{"title":"Color","type":"string","enum":["error","info","success","warning"]},"icon":{"title":"Icon (https://materialdesignicons.com)","type":"string"},"id":{"title":"ID","type":"string"},"name":{"title":"Name","type":"string"}},"required":["id","name","icon"]},"type":"array"},"timeformat":{"title":"Time Format","type":"string"}},"required":["timeformat","artifactKinds","artifactStates"]}`},
&createDocument{ID: "create-settings-global", Collection: "settings", Document: &busdb.Keyed{Key: "global", Doc: model.Settings{ArtifactStates: []*model.Type{{Icon: "mdi-help-circle-outline", ID: "unknown", Name: "Unknown", Color: pointer.String(model.TypeColorInfo)}, {Icon: "mdi-skull", ID: "malicious", Name: "Malicious", Color: pointer.String(model.TypeColorError)}, {Icon: "mdi-check", ID: "clean", Name: "Clean", Color: pointer.String(model.TypeColorSuccess)}}, ArtifactKinds: []*model.Type{{Icon: "mdi-server", ID: "asset", Name: "Asset"}, {Icon: "mdi-bullseye", ID: "ioc", Name: "IOC"}}, Timeformat: "YYYY-MM-DDThh:mm:ss"}}},
&updateSchema{ID: "update-ticket-collection", Name: "tickets", DataType: "ticket", Schema: `{"properties":{"artifacts":{"items":{"properties":{"enrichments":{"additionalProperties":{"properties":{"created":{"format":"date-time","type":"string"},"data":{"example":{"hash":"b7a067a742c20d07a7456646de89bc2d408a1153"},"properties":{},"type":"object"},"name":{"example":"hash.sha1","type":"string"}},"required":["created","data","name"],"type":"object"},"type":"object"},"name":{"example":"2.2.2.2","type":"string"},"status":{"example":"Unknown","type":"string"},"type":{"type":"string"},"kind":{"type":"string"}},"required":["name"],"type":"object"},"type":"array"},"comments":{"items":{"properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"}},"required":["created","creator","message"],"type":"object"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"example":{"description":"my little incident"},"properties":{},"type":"object"},"files":{"items":{"properties":{"key":{"example":"myfile","type":"string"},"name":{"example":"notes.docx","type":"string"}},"required":["key","name"],"type":"object"},"type":"array"},"modified":{"format":"date-time","type":"string"},"name":{"example":"WannyCry","type":"string"},"owner":{"example":"bob","type":"string"},"playbooks":{"additionalProperties":{"properties":{"name":{"example":"Phishing","type":"string"},"tasks":{"additionalProperties":{"properties":{"automation":{"type":"string"},"closed":{"format":"date-time","type":"string"},"created":{"format":"date-time","type":"string"},"data":{"properties":{},"type":"object"},"done":{"type":"boolean"},"join":{"example":false,"type":"boolean"},"payload":{"additionalProperties":{"type":"string"},"type":"object"},"name":{"example":"Inform user","type":"string"},"next":{"additionalProperties":{"type":"string"},"type":"object"},"owner":{"type":"string"},"schema":{"properties":{},"type":"object"},"type":{"enum":["task","input","automation"],"example":"task","type":"string"}},"required":["created","done","name","type"],"type":"object"},"type":"object"}},"required":["name","tasks"],"type":"object"},"type":"object"},"read":{"example":["bob"],"items":{"type":"string"},"type":"array"},"references":{"items":{"properties":{"href":{"example":"https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2017-0144","type":"string"},"name":{"example":"CVE-2017-0144","type":"string"}},"required":["href","name"],"type":"object"},"type":"array"},"schema":{"example":"{}","type":"string"},"status":{"example":"open","type":"string"},"type":{"example":"incident","type":"string"},"write":{"example":["alice"],"items":{"type":"string"},"type":"array"}},"required":["created","modified","name","schema","status","type"],"type":"object"}`},
&createCollection{ID: "create-dashboard-collection", Name: "dashboards", DataType: "dashboards", Schema: `{"type":"object","properties":{"name":{"type":"string"},"widgets":{"items":{"type":"object","properties":{"aggregation":{"type":"string"},"filter":{"type":"string"},"name":{"type":"string"},"type":{"enum":[ "bar", "line", "pie" ]},"width": { "type": "integer", "minimum": 1, "maximum": 12 }},"required":["name","aggregation", "type", "width"]},"type":"array"}},"required":["name","widgets"]}`},
}, nil
}

View File

@@ -1,208 +0,0 @@
{
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://example.com/object1618746510.json",
"title": "Advanced",
"type": "object",
"properties": {
"severity": {
"$id": "#root/severity",
"title": "Severity",
"type": "string",
"default": "Medium",
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "Low",
"title": "Low",
"icon": "mdi-chevron-up"
},
{
"const": "Medium",
"title": "Medium",
"icon": "mdi-chevron-double-up"
},
{
"const": "High",
"title": "High",
"icon": "mdi-chevron-triple-up"
}
]
},
"tlp": {
"$id": "#root/tlp",
"title": "TLP",
"type": "string",
"nx-enum": [
"White",
"Green",
"Amber",
"Red"
],
"x-cols": 6,
"x-class": "pr-2",
"x-display": "icon",
"x-itemIcon": "icon",
"oneOf": [
{
"const": "White",
"title": "White",
"icon": "mdi-alpha-w"
},
{
"const": "Green",
"title": "Green",
"icon": "mdi-alpha-g"
},
{
"const": "Amber",
"title": "Amber",
"icon": "mdi-alpha-a"
},
{
"const": "Red",
"title": "Red",
"icon": "mdi-alpha-r"
}
]
},
"description": {
"$id": "#root/description",
"title": "Description",
"type": "string",
"x-display": "textarea",
"x-class": "pr-2"
},
"type": {
"type": "object",
"title": "Select an incident type",
"oneOf": [
{
"title": "Malware",
"properties": {
"schemaKey": {
"type": "string",
"const": "malware"
},
"malware_type": {
"type": "string",
"title": "Malware Type",
"enum": ["Ransomware", "Worm", "Virus"]
}
}
},
{
"title": "Phishing",
"properties": {
"schemaKey": {
"type": "string",
"const": "phishing"
},
"phishing_type": {
"type": "string",
"title": "Phishing Type",
"enum": ["Normal", "Spear", "Whale"]
}
}
}
],
"x-cols": 12
},
"apt": {
"type": "boolean",
"x-display": "switch",
"title": "APT involved?",
"x-cols": 6
},
"apt-group": {
"type": "string",
"title": "Select APT",
"enum": ["Lazarus Group", "Equation Group", "Fancy Bear (APT 28)", "OceanLotus (APT 32)", "Other"],
"x-if": "apt",
"x-cols": 6
},
"tactics": {
"type": "array",
"title": "MITRE Att&ck",
"description": "This description is used as a help message.",
"items": {
"type": "object",
"oneOf": [
{
"title": "Reconnaissance",
"properties": {
"tactic": {
"type": "string",
"const": "reconnaissance",
"title": "Tactic",
"description": "The adversary is trying to gather information they can use to plan future operations."
},
"techniques": {
"type": "array",
"title": "Techniques",
"items": {
"type": "string",
"oneOf": [
{
"const": "T1595",
"title": "Active Scanning",
"description": "Adversaries may execute active reconnaissance scans to gather information that can be used during targeting. Active scans are those where the adversary probes victim infrastructure via network traffic, as opposed to other forms of reconnaissance that do not involve direct interaction."
},
{
"const": "T1592",
"title": "Gather Victim Host Information"
}
]
},
"minItems": 1,
"uniqueItems": true
}
}
},
{
"title": "Persistence",
"properties": {
"tactic": {
"type": "string",
"const": "persistence"
},
"techniques": {
"type": "string",
"title": "Techniques",
"oneOf": [
{
"const": "T1098",
"title": "Account Manipulation"
},
{
"const": "T1197",
"title": "BITS Jobs"
}
]
}
}
}
]
},
"uniqueItems": true
},
"tags": {
"type": "array",
"title": "Tags",
"items": {
"type": "string",
"examples": [
"misp",
"external report",
"internal report"
]
}
}
},
"required": ["severity", "description", "tactics", "type"]
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,6 @@ package database
import (
"context"
"errors"
"time"
"github.com/arangodb/go-driver"
"github.com/iancoleman/strcase"
@@ -11,7 +10,8 @@ import (
"gopkg.in/yaml.v3"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/time"
)
type PlaybookYAML struct {
@@ -29,8 +29,8 @@ type TaskYAML struct {
Join bool `yaml:"join"`
}
func toPlaybooks(docs []*models.PlaybookTemplateForm) (map[string]*models.Playbook, error) {
playbooks := map[string]*models.Playbook{}
func toPlaybooks(docs []*model.PlaybookTemplateForm) (map[string]*model.Playbook, error) {
playbooks := map[string]*model.Playbook{}
for _, doc := range docs {
playbook, err := toPlaybook(doc)
if err != nil {
@@ -45,15 +45,15 @@ func toPlaybooks(docs []*models.PlaybookTemplateForm) (map[string]*models.Playbo
return playbooks, nil
}
func toPlaybook(doc *models.PlaybookTemplateForm) (*models.Playbook, error) {
ticketPlaybook := &models.Playbook{}
func toPlaybook(doc *model.PlaybookTemplateForm) (*model.Playbook, error) {
ticketPlaybook := &model.Playbook{}
err := yaml.Unmarshal([]byte(doc.Yaml), ticketPlaybook)
if err != nil {
return nil, err
}
for idx, task := range ticketPlaybook.Tasks {
if task.Schema != nil {
task.Schema = dyno.ConvertMapI2MapS(task.Schema.(map[string]interface{}))
task.Schema = dyno.ConvertMapI2MapS(task.Schema).(map[string]interface{})
}
task.Created = time.Now().UTC()
ticketPlaybook.Tasks[idx] = task
@@ -61,11 +61,11 @@ func toPlaybook(doc *models.PlaybookTemplateForm) (*models.Playbook, error) {
return ticketPlaybook, nil
}
func toPlaybookTemplateResponse(key string, doc *models.PlaybookTemplate) *models.PlaybookTemplateResponse {
return &models.PlaybookTemplateResponse{ID: key, Name: doc.Name, Yaml: doc.Yaml}
func toPlaybookTemplateResponse(key string, doc *model.PlaybookTemplate) *model.PlaybookTemplateResponse {
return &model.PlaybookTemplateResponse{ID: key, Name: doc.Name, Yaml: doc.Yaml}
}
func (db *Database) PlaybookCreate(ctx context.Context, playbook *models.PlaybookTemplateForm) (*models.PlaybookTemplateResponse, error) {
func (db *Database) PlaybookCreate(ctx context.Context, playbook *model.PlaybookTemplateForm) (*model.PlaybookTemplateResponse, error) {
if playbook == nil {
return nil, errors.New("requires playbook")
}
@@ -79,9 +79,9 @@ func (db *Database) PlaybookCreate(ctx context.Context, playbook *models.Playboo
if playbookYAML.Name == "" {
return nil, errors.New("requires template name")
}
p := models.PlaybookTemplate{Name: playbookYAML.Name, Yaml: playbook.Yaml}
p := model.PlaybookTemplate{Name: playbookYAML.Name, Yaml: playbook.Yaml}
var doc models.PlaybookTemplate
var doc model.PlaybookTemplate
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.playbookCollection.CreateDocument(ctx, newctx, strcase.ToKebab(playbookYAML.Name), p)
@@ -92,8 +92,8 @@ func (db *Database) PlaybookCreate(ctx context.Context, playbook *models.Playboo
return toPlaybookTemplateResponse(meta.Key, &doc), nil
}
func (db *Database) PlaybookGet(ctx context.Context, id string) (*models.PlaybookTemplateResponse, error) {
doc := models.PlaybookTemplate{}
func (db *Database) PlaybookGet(ctx context.Context, id string) (*model.PlaybookTemplateResponse, error) {
doc := model.PlaybookTemplate{}
meta, err := db.playbookCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -107,7 +107,7 @@ func (db *Database) PlaybookDelete(ctx context.Context, id string) error {
return err
}
func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *models.PlaybookTemplateForm) (*models.PlaybookTemplateResponse, error) {
func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *model.PlaybookTemplateForm) (*model.PlaybookTemplateResponse, error) {
var pb PlaybookYAML
err := yaml.Unmarshal([]byte(playbook.Yaml), &pb)
if err != nil {
@@ -118,10 +118,10 @@ func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *mod
return nil, errors.New("requires template name")
}
var doc models.PlaybookTemplate
var doc model.PlaybookTemplate
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.playbookCollection.ReplaceDocument(ctx, id, models.PlaybookTemplate{Name: pb.Name, Yaml: playbook.Yaml})
meta, err := db.playbookCollection.ReplaceDocument(ctx, id, model.PlaybookTemplate{Name: pb.Name, Yaml: playbook.Yaml})
if err != nil {
return nil, err
}
@@ -129,16 +129,16 @@ func (db *Database) PlaybookUpdate(ctx context.Context, id string, playbook *mod
return toPlaybookTemplateResponse(meta.Key, &doc), nil
}
func (db *Database) PlaybookList(ctx context.Context) ([]*models.PlaybookTemplateResponse, error) {
func (db *Database) PlaybookList(ctx context.Context) ([]*model.PlaybookTemplateResponse, error) {
query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": PlaybookCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.PlaybookTemplateResponse
var docs []*model.PlaybookTemplateResponse
for {
var doc models.PlaybookTemplate
var doc model.PlaybookTemplate
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break

View File

@@ -8,10 +8,10 @@ import (
"github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/dag"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func playbookGraph(playbook *models.Playbook) (*dag.Graph, error) {
func playbookGraph(playbook *model.Playbook) (*dag.Graph, error) {
d := dag.NewGraph()
var taskIDs []string
@@ -36,13 +36,13 @@ func playbookGraph(playbook *models.Playbook) (*dag.Graph, error) {
return d, nil
}
func toTaskResponse(playbook *models.Playbook, taskID string, order int, graph *dag.Graph) (*models.TaskResponse, error) {
func toTaskResponse(playbook *model.Playbook, taskID string, order int, graph *dag.Graph) (*model.TaskResponse, error) {
task, ok := playbook.Tasks[taskID]
if !ok {
return nil, fmt.Errorf("task %s not found", taskID)
}
tr := &models.TaskResponse{
tr := &model.TaskResponse{
Automation: task.Automation,
Closed: task.Closed,
Created: task.Created,
@@ -67,7 +67,7 @@ func toTaskResponse(playbook *models.Playbook, taskID string, order int, graph *
return tr, nil
}
func activePlaybook(playbook *models.Playbook, taskID string) (bool, error) {
func activePlaybook(playbook *model.Playbook, taskID string) (bool, error) {
task, ok := playbook.Tasks[taskID]
if !ok {
return false, fmt.Errorf("playbook does not contain tasks %s", taskID)
@@ -81,7 +81,7 @@ func activePlaybook(playbook *models.Playbook, taskID string) (bool, error) {
return active(playbook, taskID, d, task)
}
func active(playbook *models.Playbook, taskID string, d *dag.Graph, task *models.Task) (bool, error) {
func active(playbook *model.Playbook, taskID string, d *dag.Graph, task *model.Task) (bool, error) {
if task.Done {
return false, nil
}
@@ -165,7 +165,7 @@ func evalRequirement(aql string, data interface{}) (bool, error) {
/*
// "github.com/qri-io/jsonschema"
func valid(task *models.Task) (bool, error) {
func valid(task *model.Task) (bool, error) {
schema, err := json.Marshal(task.Schema)
if err != nil {
return false, err

View File

@@ -5,12 +5,12 @@ import (
"github.com/stretchr/testify/assert"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
var playbook2 = &models.Playbook{
var playbook2 = &model.Playbook{
Name: "Phishing",
Tasks: map[string]*models.Task{
Tasks: map[string]*model.Task{
"board": {Next: map[string]string{
"escalate": "boardInvolved == true",
"aquire-mail": "boardInvolved == false",
@@ -30,9 +30,9 @@ var playbook2 = &models.Playbook{
},
}
var playbook3 = &models.Playbook{
var playbook3 = &model.Playbook{
Name: "Phishing",
Tasks: map[string]*models.Task{
Tasks: map[string]*model.Task{
"board": {Next: map[string]string{
"escalate": "boardInvolved == true",
"aquire-mail": "boardInvolved == false",
@@ -52,9 +52,9 @@ var playbook3 = &models.Playbook{
},
}
var playbook4 = &models.Playbook{
var playbook4 = &model.Playbook{
Name: "Malware",
Tasks: map[string]*models.Task{
Tasks: map[string]*model.Task{
"file-or-hash": {Next: map[string]string{
"enter-hash": "file == 'Hash'",
"upload": "file == 'File'",
@@ -72,7 +72,7 @@ var playbook4 = &models.Playbook{
func Test_canBeCompleted(t *testing.T) {
type args struct {
playbook *models.Playbook
playbook *model.Playbook
taskID string
}
tests := []struct {
@@ -106,7 +106,7 @@ func Test_canBeCompleted(t *testing.T) {
func Test_playbookOrder(t *testing.T) {
type args struct {
playbook *models.Playbook
playbook *model.Playbook
}
tests := []struct {
name string

View File

@@ -7,6 +7,7 @@ import (
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb"
)
@@ -37,12 +38,11 @@ func (db *Database) RelatedRemove(ctx context.Context, id, id2 int64) error {
"id": driver.DocumentID(TicketCollectionName + "/" + strconv.Itoa(int(id))),
"id2": driver.DocumentID(TicketCollectionName + "/" + strconv.Itoa(int(id2))),
}, &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(TicketCollectionName + "/" + strconv.Itoa(int(id))),
driver.DocumentID(TicketCollectionName + "/" + strconv.Itoa(int(id2))),
},
Msg: "Removed ticket/artifact relation",
})
return err
}

View File

@@ -2,85 +2,34 @@ package database
import (
"context"
"errors"
"github.com/arangodb/go-driver"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toUserDataResponse(key string, doc *models.UserData) *models.UserDataResponse {
return &models.UserDataResponse{
Email: doc.Email,
ID: key,
Image: doc.Image,
Name: doc.Name,
Timeformat: doc.Timeformat,
func (db *Database) Settings(ctx context.Context) (*model.Settings, error) {
settings := &model.Settings{}
if _, err := db.settingsCollection.ReadDocument(ctx, "global", settings); err != nil {
return nil, err
}
return settings, nil
}
func (db *Database) UserDataCreate(ctx context.Context, id string, userdata *models.UserData) error {
if userdata == nil {
return errors.New("requires setting")
}
if id == "" {
return errors.New("requires username")
}
_, err := db.userdataCollection.CreateDocument(ctx, ctx, id, userdata)
return err
}
func (db *Database) UserDataGetOrCreate(ctx *gin.Context, id string, newUserData *models.UserData) (*models.UserDataResponse, error) {
setting, err := db.UserDataGet(ctx, id)
if err != nil {
return toUserDataResponse(id, newUserData), db.UserDataCreate(ctx, id, newUserData)
}
return setting, nil
}
func (db *Database) UserDataGet(ctx context.Context, id string) (*models.UserDataResponse, error) {
var doc models.UserData
meta, err := db.userdataCollection.ReadDocument(ctx, id, &doc)
func (db *Database) SaveSettings(ctx context.Context, settings *model.Settings) (*model.Settings, error) {
exists, err := db.settingsCollection.DocumentExists(ctx, "global")
if err != nil {
return nil, err
}
return toUserDataResponse(meta.Key, &doc), err
}
func (db *Database) UserDataList(ctx context.Context) ([]*models.UserDataResponse, error) {
query := "FOR d IN @@collection SORT d.username ASC RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserDataCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.UserDataResponse
for {
var doc models.UserData
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break
} else if err != nil {
if exists {
if _, err := db.settingsCollection.ReplaceDocument(ctx, "global", settings); err != nil {
return nil, err
}
} else {
if _, err := db.settingsCollection.CreateDocument(ctx, ctx, "global", settings); err != nil {
return nil, err
}
docs = append(docs, toUserDataResponse(meta.Key, &doc))
}
return docs, err
}
func (db *Database) UserDataUpdate(ctx context.Context, id string, userdata *models.UserData) (*models.UserDataResponse, error) {
var doc models.UserData
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.userdataCollection.ReplaceDocument(ctx, id, userdata)
if err != nil {
return nil, err
}
return toUserDataResponse(meta.Key, &doc), nil
return settings, nil
}

View File

@@ -2,12 +2,14 @@ package database
import (
"context"
"fmt"
"github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func (db *Database) Statistics(ctx context.Context) (*models.Statistics, error) {
func (db *Database) Statistics(ctx context.Context) (*model.Statistics, error) {
query := `RETURN {
tickets_per_type: MERGE(FOR d in tickets
COLLECT type = d.type WITH COUNT INTO typecount
@@ -34,10 +36,56 @@ func (db *Database) Statistics(ctx context.Context) (*models.Statistics, error)
}
defer cur.Close()
statistics := models.Statistics{}
statistics := model.Statistics{}
if _, err := cur.ReadDocument(ctx, &statistics); err != nil {
return nil, err
}
return &statistics, nil
}
func (db *Database) WidgetData(ctx context.Context, aggregation string, filter *string) (map[string]interface{}, error) {
parser := &caql.Parser{Searcher: db.Index, Prefix: "d."}
queryTree, err := parser.Parse(aggregation)
if err != nil {
return nil, fmt.Errorf("invalid aggregation query (%s): syntax error\n", aggregation)
}
aggregationString, err := queryTree.String()
if err != nil {
return nil, fmt.Errorf("invalid widget aggregation query (%s): %w", aggregation, err)
}
aggregation = aggregationString
filterQ := ""
if filter != nil && *filter != "" {
queryTree, err := parser.Parse(*filter)
if err != nil {
return nil, fmt.Errorf("invalid filter query (%s): syntax error\n", *filter)
}
filterString, err := queryTree.String()
if err != nil {
return nil, fmt.Errorf("invalid widget filter query (%s): %w", *filter, err)
}
filterQ = "FILTER " + filterString
}
query := `RETURN MERGE(FOR d in tickets
` + filterQ + `
COLLECT field = ` + aggregation + ` WITH COUNT INTO count
RETURN ZIP([field], [count]))`
cur, _, err := db.Query(ctx, query, nil, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cur.Close()
statistics := map[string]interface{}{}
if _, err := cur.ReadDocument(ctx, &statistics); err != nil {
return nil, err
}
return statistics, nil
}

View File

@@ -6,18 +6,18 @@ import (
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
type playbookResponse struct {
PlaybookId string `json:"playbook_id"`
PlaybookName string `json:"playbook_name"`
Playbook models.Playbook `json:"playbook"`
TicketId int64 `json:"ticket_id"`
TicketName string `json:"ticket_name"`
PlaybookId string `json:"playbook_id"`
PlaybookName string `json:"playbook_name"`
Playbook model.Playbook `json:"playbook"`
TicketId int64 `json:"ticket_id"`
TicketName string `json:"ticket_name"`
}
func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, error) {
func (db *Database) TaskList(ctx context.Context) ([]*model.TaskWithContext, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -35,7 +35,7 @@ func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, er
return nil, err
}
defer cursor.Close()
docs := []*models.TaskWithContext{}
var docs []*model.TaskWithContext
for {
var doc playbookResponse
_, err := cursor.ReadDocument(ctx, &doc)
@@ -45,7 +45,6 @@ func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, er
return nil, err
}
playbook, err := toPlaybookResponse(&doc.Playbook)
if err != nil {
return nil, err
@@ -53,10 +52,10 @@ func (db *Database) TaskList(ctx context.Context) ([]*models.TaskWithContext, er
for _, task := range playbook.Tasks {
if task.Active {
docs = append(docs, &models.TaskWithContext{
docs = append(docs, &model.TaskWithContext{
PlaybookId: doc.PlaybookId,
PlaybookName: doc.PlaybookName,
Task: *task,
Task: task,
TicketId: doc.TicketId,
TicketName: doc.TicketName,
})

View File

@@ -8,18 +8,18 @@ import (
"github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toTicketTemplate(doc *models.TicketTemplateForm) *models.TicketTemplate {
return &models.TicketTemplate{Name: doc.Name, Schema: doc.Schema}
func toTicketTemplate(doc *model.TicketTemplateForm) *model.TicketTemplate {
return &model.TicketTemplate{Name: doc.Name, Schema: doc.Schema}
}
func toTicketTemplateResponse(key string, doc *models.TicketTemplate) *models.TicketTemplateResponse {
return &models.TicketTemplateResponse{ID: key, Name: doc.Name, Schema: doc.Schema}
func toTicketTemplateResponse(key string, doc *model.TicketTemplate) *model.TicketTemplateResponse {
return &model.TicketTemplateResponse{ID: key, Name: doc.Name, Schema: doc.Schema}
}
func (db *Database) TemplateCreate(ctx context.Context, template *models.TicketTemplateForm) (*models.TicketTemplateResponse, error) {
func (db *Database) TemplateCreate(ctx context.Context, template *model.TicketTemplateForm) (*model.TicketTemplateResponse, error) {
if template == nil {
return nil, errors.New("requires template")
}
@@ -27,7 +27,7 @@ func (db *Database) TemplateCreate(ctx context.Context, template *models.TicketT
return nil, errors.New("requires template name")
}
var doc models.TicketTemplate
var doc model.TicketTemplate
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.templateCollection.CreateDocument(ctx, newctx, strcase.ToKebab(template.Name), toTicketTemplate(template))
@@ -38,8 +38,8 @@ func (db *Database) TemplateCreate(ctx context.Context, template *models.TicketT
return toTicketTemplateResponse(meta.Key, &doc), nil
}
func (db *Database) TemplateGet(ctx context.Context, id string) (*models.TicketTemplateResponse, error) {
var doc models.TicketTemplate
func (db *Database) TemplateGet(ctx context.Context, id string) (*model.TicketTemplateResponse, error) {
var doc model.TicketTemplate
meta, err := db.templateCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -48,8 +48,8 @@ func (db *Database) TemplateGet(ctx context.Context, id string) (*models.TicketT
return toTicketTemplateResponse(meta.Key, &doc), nil
}
func (db *Database) TemplateUpdate(ctx context.Context, id string, template *models.TicketTemplateForm) (*models.TicketTemplateResponse, error) {
var doc models.TicketTemplate
func (db *Database) TemplateUpdate(ctx context.Context, id string, template *model.TicketTemplateForm) (*model.TicketTemplateResponse, error) {
var doc model.TicketTemplate
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.templateCollection.ReplaceDocument(ctx, id, toTicketTemplate(template))
@@ -65,16 +65,16 @@ func (db *Database) TemplateDelete(ctx context.Context, id string) error {
return err
}
func (db *Database) TemplateList(ctx context.Context) ([]*models.TicketTemplateResponse, error) {
func (db *Database) TemplateList(ctx context.Context) ([]*model.TicketTemplateResponse, error) {
query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": TemplateCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.TicketTemplateResponse
var docs []*model.TicketTemplateResponse
for {
var doc models.TicketTemplate
var doc model.TicketTemplate
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break

View File

@@ -6,22 +6,22 @@ import (
"github.com/stretchr/testify/assert"
"github.com/SecurityBrewery/catalyst/database/migrations"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/test"
)
var template1 = &models.TicketTemplateForm{
var template1 = &model.TicketTemplateForm{
Schema: migrations.DefaultTemplateSchema,
Name: "Template 1",
}
var default1 = &models.TicketTemplateForm{
var default1 = &model.TicketTemplateForm{
Schema: migrations.DefaultTemplateSchema,
Name: "Default",
}
func TestDatabase_TemplateCreate(t *testing.T) {
type args struct {
template *models.TicketTemplateForm
template *model.TicketTemplateForm
}
tests := []struct {
name string
@@ -31,8 +31,8 @@ func TestDatabase_TemplateCreate(t *testing.T) {
{name: "Normal", args: args{template: template1}},
{name: "Duplicate", args: args{template: default1}, wantErr: true},
{name: "Nil template", args: args{}, wantErr: true},
{name: "Template without fields", args: args{template: &models.TicketTemplateForm{}}, wantErr: true},
{name: "Only name", args: args{template: &models.TicketTemplateForm{Name: "name"}}, wantErr: false},
{name: "Template without fields", args: args{template: &model.TicketTemplateForm{}}, wantErr: true},
{name: "Only name", args: args{template: &model.TicketTemplateForm{Name: "name"}}, wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -87,10 +87,10 @@ func TestDatabase_TemplateGet(t *testing.T) {
tests := []struct {
name string
args args
want *models.TicketTemplateResponse
want *model.TicketTemplateResponse
wantErr bool
}{
{name: "Normal", args: args{id: "default"}, want: &models.TicketTemplateResponse{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}},
{name: "Normal", args: args{id: "default"}, want: &model.TicketTemplateResponse{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}},
{name: "Not existing", args: args{id: "foobar"}, wantErr: true},
}
for _, tt := range tests {
@@ -122,10 +122,10 @@ func TestDatabase_TemplateGet(t *testing.T) {
func TestDatabase_TemplateList(t *testing.T) {
tests := []struct {
name string
want []*models.TicketTemplateResponse
want []*model.TicketTemplateResponse
wantErr bool
}{
{name: "Normal", want: []*models.TicketTemplateResponse{{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}, {ID: "template-1", Name: template1.Name, Schema: template1.Schema}}},
{name: "Normal", want: []*model.TicketTemplateResponse{{ID: "default", Name: "Default", Schema: migrations.DefaultTemplateSchema}, {ID: "template-1", Name: template1.Name, Schema: template1.Schema}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -152,7 +152,7 @@ func TestDatabase_TemplateList(t *testing.T) {
func TestDatabase_TemplateUpdate(t *testing.T) {
type args struct {
id string
template *models.TicketTemplateForm
template *model.TicketTemplateForm
}
tests := []struct {
name string

View File

@@ -9,24 +9,25 @@ import (
"strconv"
"strings"
"sync"
"time"
"github.com/arangodb/go-driver"
"github.com/xeipuuv/gojsonschema"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/caql"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/time"
"github.com/SecurityBrewery/catalyst/index"
)
func toTicket(ticketForm *models.TicketForm) (interface{}, error) {
func toTicket(ticketForm *model.TicketForm) (interface{}, error) {
playbooks, err := toPlaybooks(ticketForm.Playbooks)
if err != nil {
return nil, err
}
ticket := &models.Ticket{
ticket := &model.Ticket{
Artifacts: ticketForm.Artifacts,
Comments: ticketForm.Comments,
Details: ticketForm.Details,
@@ -69,8 +70,8 @@ func toTicket(ticketForm *models.TicketForm) (interface{}, error) {
return ticket, nil
}
func toTicketResponses(tickets []*models.TicketSimpleResponse) ([]*models.TicketResponse, error) {
var extendedTickets []*models.TicketResponse
func toTicketResponses(tickets []*model.TicketSimpleResponse) ([]*model.TicketResponse, error) {
var extendedTickets []*model.TicketResponse
for _, simple := range tickets {
tr, err := toTicketResponse(simple)
if err != nil {
@@ -81,13 +82,13 @@ func toTicketResponses(tickets []*models.TicketSimpleResponse) ([]*models.Ticket
return extendedTickets, nil
}
func toTicketResponse(ticket *models.TicketSimpleResponse) (*models.TicketResponse, error) {
func toTicketResponse(ticket *model.TicketSimpleResponse) (*model.TicketResponse, error) {
playbooks, err := toPlaybookResponses(ticket.Playbooks)
if err != nil {
return nil, err
}
return &models.TicketResponse{
return &model.TicketResponse{
ID: ticket.ID,
Artifacts: ticket.Artifacts,
Comments: ticket.Comments,
@@ -107,13 +108,13 @@ func toTicketResponse(ticket *models.TicketSimpleResponse) (*models.TicketRespon
}, nil
}
func toTicketSimpleResponse(key string, ticket *models.Ticket) (*models.TicketSimpleResponse, error) {
func toTicketSimpleResponse(key string, ticket *model.Ticket) (*model.TicketSimpleResponse, error) {
id, err := strconv.ParseInt(key, 10, 64)
if err != nil {
return nil, err
}
return &models.TicketSimpleResponse{
return &model.TicketSimpleResponse{
Artifacts: ticket.Artifacts,
Comments: ticket.Comments,
Created: ticket.Created,
@@ -133,8 +134,8 @@ func toTicketSimpleResponse(key string, ticket *models.Ticket) (*models.TicketSi
}, nil
}
func toTicketWithTickets(ticketResponse *models.TicketResponse, tickets []*models.TicketSimpleResponse) *models.TicketWithTickets {
return &models.TicketWithTickets{
func toTicketWithTickets(ticketResponse *model.TicketResponse, tickets []*model.TicketSimpleResponse, logs []*model.LogEntry) *model.TicketWithTickets {
return &model.TicketWithTickets{
Artifacts: ticketResponse.Artifacts,
Comments: ticketResponse.Comments,
Created: ticketResponse.Created,
@@ -152,12 +153,13 @@ func toTicketWithTickets(ticketResponse *models.TicketResponse, tickets []*model
Type: ticketResponse.Type,
Write: ticketResponse.Write,
Logs: logs,
Tickets: tickets,
}
}
func toPlaybookResponses(playbooks map[string]*models.Playbook) (map[string]*models.PlaybookResponse, error) {
pr := map[string]*models.PlaybookResponse{}
func toPlaybookResponses(playbooks map[string]*model.Playbook) (map[string]*model.PlaybookResponse, error) {
pr := map[string]*model.PlaybookResponse{}
var err error
for k, v := range playbooks {
pr[k], err = toPlaybookResponse(v)
@@ -168,15 +170,15 @@ func toPlaybookResponses(playbooks map[string]*models.Playbook) (map[string]*mod
return pr, nil
}
func toPlaybookResponse(playbook *models.Playbook) (*models.PlaybookResponse, error) {
func toPlaybookResponse(playbook *model.Playbook) (*model.PlaybookResponse, error) {
graph, err := playbookGraph(playbook)
if err != nil {
return nil, err
}
re := &models.PlaybookResponse{
re := &model.PlaybookResponse{
Name: playbook.Name,
Tasks: map[string]*models.TaskResponse{},
Tasks: map[string]*model.TaskResponse{},
}
results, err := graph.Toposort()
@@ -196,7 +198,7 @@ func toPlaybookResponse(playbook *models.Playbook) (*models.PlaybookResponse, er
return re, nil
}
func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*models.TicketForm) ([]*models.TicketResponse, error) {
func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*model.TicketForm) ([]*model.TicketResponse, error) {
update, err := db.Hooks.IngestionFilter(ctx, db.Index)
if err != nil {
return nil, err
@@ -209,7 +211,7 @@ func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*models
return nil, err
}
if err := validate(ticket, models.TicketSchema); err != nil {
if err := validate(ticket, model.TicketSchema); err != nil {
return nil, err
}
@@ -244,9 +246,8 @@ func (db *Database) TicketBatchCreate(ctx context.Context, ticketForms []*models
for _, apiTicket := range apiTickets {
ids = append(ids, driver.NewDocumentID(TicketCollectionName, fmt.Sprint(apiTicket.ID)))
}
if err := db.BusDatabase.LogAndNotify(ctx, ids, "Ticket created"); err != nil {
return nil, err
}
go db.bus.PublishDatabaseUpdate(ids, bus.DatabaseEntryUpdated)
ticketResponses, err := toTicketResponses(apiTickets)
if err != nil {
@@ -277,26 +278,26 @@ func (db *Database) IndexRebuild(ctx context.Context) error {
return batchIndex(db.Index, tickets)
}
func batchIndex(index *index.Index, tickets []*models.TicketSimpleResponse) error {
func batchIndex(index *index.Index, tickets []*model.TicketSimpleResponse) error {
var wg sync.WaitGroup
var batch []*models.TicketSimpleResponse
var batch []*model.TicketSimpleResponse
for _, ticket := range tickets {
batch = append(batch, ticket)
if len(batch) > 100 {
wg.Add(1)
go func(docs []*models.TicketSimpleResponse) {
go func(docs []*model.TicketSimpleResponse) {
index.Index(docs)
wg.Done()
}(batch)
batch = []*models.TicketSimpleResponse{}
batch = []*model.TicketSimpleResponse{}
}
}
wg.Wait()
return nil
}
func (db *Database) TicketGet(ctx context.Context, ticketID int64) (*models.TicketWithTickets, error) {
func (db *Database) TicketGet(ctx context.Context, ticketID int64) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketReadFilter(ctx)
if err != nil {
return nil, err
@@ -305,7 +306,7 @@ func (db *Database) TicketGet(ctx context.Context, ticketID int64) (*models.Tick
return db.ticketGetQuery(ctx, ticketID, `LET d = DOCUMENT(@@collection, @ID) `+ticketFilterQuery+` RETURN d`, ticketFilterVars, busdb.ReadOperation)
}
func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query string, bindVars map[string]interface{}, operation *busdb.Operation) (*models.TicketWithTickets, error) {
func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query string, bindVars map[string]interface{}, operation *busdb.Operation) (*model.TicketWithTickets, error) {
if bindVars == nil {
bindVars = map[string]interface{}{}
}
@@ -320,7 +321,7 @@ func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query st
}
defer cur.Close()
ticket := models.Ticket{}
ticket := model.Ticket{}
meta, err := cur.ReadDocument(ctx, &ticket)
if err != nil {
return nil, err
@@ -332,7 +333,7 @@ func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query st
}
// index
go db.Index.Index([]*models.TicketSimpleResponse{ticketSimpleResponse})
go db.Index.Index([]*model.TicketSimpleResponse{ticketSimpleResponse})
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketReadFilter(ctx)
if err != nil {
@@ -405,10 +406,15 @@ func (db *Database) ticketGetQuery(ctx context.Context, ticketID int64, query st
return nil, err
}
return toTicketWithTickets(ticketResponse, tickets), nil
logs, err := db.LogList(ctx, fmt.Sprintf("%s/%d", TicketCollectionName, ticketID))
if err != nil {
return nil, err
}
return toTicketWithTickets(ticketResponse, tickets, logs), nil
}
func (db *Database) TicketUpdate(ctx context.Context, ticketID int64, ticket *models.Ticket) (*models.TicketWithTickets, error) {
func (db *Database) TicketUpdate(ctx context.Context, ticketID int64, ticket *model.Ticket) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -420,10 +426,9 @@ func (db *Database) TicketUpdate(ctx context.Context, ticketID int64, ticket *mo
RETURN NEW`
ticket.Modified = time.Now().UTC() // TODO make setable?
return db.ticketGetQuery(ctx, ticketID, query, mergeMaps(map[string]interface{}{"ticket": ticket}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update, Ids: []driver.DocumentID{
Type: bus.DatabaseEntryUpdated, Ids: []driver.DocumentID{
driver.NewDocumentID(TicketCollectionName, strconv.FormatInt(ticketID, 10)),
},
Msg: "Ticket updated",
})
}
@@ -441,11 +446,9 @@ func (db *Database) TicketDelete(ctx context.Context, ticketID int64) error {
return nil
}
func (db *Database) TicketList(ctx context.Context, ticketType string, query string, sorts []string, desc []bool, offset, count int64) (*models.TicketList, error) {
func (db *Database) TicketList(ctx context.Context, ticketType string, query string, sorts []string, desc []bool, offset, count int64) (*model.TicketList, error) {
binVars := map[string]interface{}{}
parser := &caql.Parser{Searcher: db.Index, Prefix: "d."}
var typeString = ""
if ticketType != "" {
typeString = "FILTER d.type == @type "
@@ -454,6 +457,7 @@ func (db *Database) TicketList(ctx context.Context, ticketType string, query str
var filterString = ""
if query != "" {
parser := &caql.Parser{Searcher: db.Index, Prefix: "d."}
queryTree, err := parser.Parse(query)
if err != nil {
return nil, errors.New("invalid filter query: syntax error")
@@ -489,14 +493,14 @@ func (db *Database) TicketList(ctx context.Context, ticketType string, query str
RETURN d`
// RETURN KEEP(d, "_key", "id", "name", "type", "created")`
ticketList, _, err := db.ticketListQuery(ctx, q, mergeMaps(binVars, ticketFilterVars), busdb.ReadOperation)
return &models.TicketList{
return &model.TicketList{
Count: documentCount,
Tickets: ticketList,
}, err
// return map[string]interface{}{"tickets": ticketList, "count": documentCount}, err
}
func (db *Database) ticketListQuery(ctx context.Context, query string, bindVars map[string]interface{}, operation *busdb.Operation) ([]*models.TicketSimpleResponse, *models.LogEntry, error) {
func (db *Database) ticketListQuery(ctx context.Context, query string, bindVars map[string]interface{}, operation *busdb.Operation) ([]*model.TicketSimpleResponse, *model.LogEntry, error) {
if bindVars == nil {
bindVars = map[string]interface{}{}
}
@@ -508,9 +512,9 @@ func (db *Database) ticketListQuery(ctx context.Context, query string, bindVars
}
defer cursor.Close()
var docs []*models.TicketSimpleResponse
var docs []*model.TicketSimpleResponse
for {
doc := models.Ticket{}
doc := model.Ticket{}
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break

View File

@@ -4,18 +4,19 @@ import (
"context"
"errors"
"fmt"
"time"
"github.com/arangodb/go-driver"
"github.com/iancoleman/strcase"
"github.com/mingrammer/commonregex"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/pointer"
"github.com/SecurityBrewery/catalyst/generated/time"
)
func (db *Database) AddArtifact(ctx context.Context, id int64, artifact *models.Artifact) (*models.TicketWithTickets, error) {
func (db *Database) AddArtifact(ctx context.Context, id int64, artifact *model.Artifact) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -31,14 +32,13 @@ func (db *Database) AddArtifact(ctx context.Context, id int64, artifact *models.
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "artifacts": PUSH(NOT_NULL(d.artifacts, []), @artifact) } IN @@collection
UPDATE d WITH { "modified": @now, "artifacts": PUSH(NOT_NULL(d.artifacts, []), @artifact) } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"artifact": artifact}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"artifact": artifact, "now": time.Now().UTC()}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Add artifact",
})
}
@@ -60,7 +60,7 @@ func inferType(name string) string {
return "unknown"
}
func (db *Database) RemoveArtifact(ctx context.Context, id int64, name string) (*models.TicketWithTickets, error) {
func (db *Database) RemoveArtifact(ctx context.Context, id int64, name string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -71,18 +71,17 @@ func (db *Database) RemoveArtifact(ctx context.Context, id int64, name string) (
FOR a IN NOT_NULL(d.artifacts, [])
FILTER a.name == @name
LET newartifacts = REMOVE_VALUE(d.artifacts, a)
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "artifacts": newartifacts } IN @@collection
UPDATE d WITH { "modified": @now, "artifacts": newartifacts } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"name": name}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"name": name, "now": time.Now().UTC()}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Remove artifact",
})
}
func (db *Database) SetTemplate(ctx context.Context, id int64, schema string) (*models.TicketWithTickets, error) {
func (db *Database) SetTemplate(ctx context.Context, id int64, schema string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -93,15 +92,14 @@ func (db *Database) SetTemplate(ctx context.Context, id int64, schema string) (*
UPDATE d WITH { "schema": @schema } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"schema": schema}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Set Template",
})
}
func (db *Database) AddComment(ctx context.Context, id int64, comment *models.CommentForm) (*models.TicketWithTickets, error) {
func (db *Database) AddComment(ctx context.Context, id int64, comment *model.CommentForm) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -122,18 +120,17 @@ func (db *Database) AddComment(ctx context.Context, id int64, comment *models.Co
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "comments": PUSH(NOT_NULL(d.comments, []), @comment) } IN @@collection
UPDATE d WITH { "modified": @now, "comments": PUSH(NOT_NULL(d.comments, []), @comment) } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"comment": comment}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"comment": comment, "now": time.Now().UTC()}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Add comment",
})
}
func (db *Database) RemoveComment(ctx context.Context, id int64, commentID int64) (*models.TicketWithTickets, error) {
func (db *Database) RemoveComment(ctx context.Context, id int64, commentID int64) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -141,18 +138,17 @@ func (db *Database) RemoveComment(ctx context.Context, id int64, commentID int64
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "comments": REMOVE_NTH(d.comments, @commentID) } IN @@collection
UPDATE d WITH { "modified": @now, "comments": REMOVE_NTH(d.comments, @commentID) } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"commentID": commentID}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"commentID": commentID, "now": time.Now().UTC()}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Remove comment",
})
}
func (db *Database) SetReferences(ctx context.Context, id int64, references []*models.Reference) (*models.TicketWithTickets, error) {
func (db *Database) SetReferences(ctx context.Context, id int64, references []*model.Reference) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -160,18 +156,17 @@ func (db *Database) SetReferences(ctx context.Context, id int64, references []*m
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "references": @references } IN @@collection
UPDATE d WITH { "modified": @now, "references": @references } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"references": references}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"references": references, "now": time.Now().UTC()}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Changed references",
})
}
func (db *Database) LinkFiles(ctx context.Context, id int64, files []*models.File) (*models.TicketWithTickets, error) {
func (db *Database) AddFile(ctx context.Context, id int64, file *model.File) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -179,18 +174,17 @@ func (db *Database) LinkFiles(ctx context.Context, id int64, files []*models.Fil
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "files": @files } IN @@collection
UPDATE d WITH { "modified": @now, "files": APPEND(NOT_NULL(d.files, []), [@file]) } IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"files": files}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{"file": file, "now": time.Now().UTC()}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.DocumentID(fmt.Sprintf("%s/%d", TicketCollectionName, id)),
},
Msg: "Linked files",
})
}
func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTemplate *models.PlaybookTemplateForm) (*models.TicketWithTickets, error) {
func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTemplate *model.PlaybookTemplateForm) (*model.TicketWithTickets, error) {
pb, err := toPlaybook(playbookTemplate)
if err != nil {
return nil, err
@@ -216,18 +210,18 @@ func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTem
FILTER d._key == @ID
LET newplaybook = ZIP( [@playbookID], [@playbook] )
LET newplaybooks = MERGE(NOT_NULL(d.playbooks, {}), newplaybook)
LET newticket = MERGE(d, { "modified": DATE_ISO8601(DATE_NOW()), "playbooks": newplaybooks })
LET newticket = MERGE(d, { "modified": @now, "playbooks": newplaybooks })
REPLACE d WITH newticket IN @@collection
RETURN NEW`
ticket, err := db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{
"playbook": pb,
"playbookID": findName(parentTicket.Playbooks, playbookID),
"now": time.Now().UTC(),
}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.NewDocumentID(TicketCollectionName, fmt.Sprintf("%d", id)),
},
Msg: "Added playbook",
})
if err != nil {
return nil, err
@@ -240,7 +234,7 @@ func (db *Database) AddTicketPlaybook(ctx context.Context, id int64, playbookTem
return ticket, nil
}
func findName(playbooks map[string]*models.PlaybookResponse, name string) string {
func findName(playbooks map[string]*model.PlaybookResponse, name string) string {
if _, ok := playbooks[name]; !ok {
return name
}
@@ -253,10 +247,10 @@ func findName(playbooks map[string]*models.PlaybookResponse, name string) string
}
}
func runRootTask(ticket *models.TicketResponse, playbookID string, db *Database) error {
func runRootTask(ticket *model.TicketResponse, playbookID string, db *Database) error {
playbook := ticket.Playbooks[playbookID]
var root *models.TaskResponse
var root *model.TaskResponse
for _, task := range playbook.Tasks {
if task.Order == 0 {
root = task
@@ -267,7 +261,7 @@ func runRootTask(ticket *models.TicketResponse, playbookID string, db *Database)
return nil
}
func (db *Database) RemoveTicketPlaybook(ctx context.Context, id int64, playbookID string) (*models.TicketWithTickets, error) {
func (db *Database) RemoveTicketPlaybook(ctx context.Context, id int64, playbookID string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -277,15 +271,15 @@ func (db *Database) RemoveTicketPlaybook(ctx context.Context, id int64, playbook
` + ticketFilterQuery + `
FILTER d._key == @ID
LET newplaybooks = UNSET(d.playbooks, @playbookID)
REPLACE d WITH MERGE(d, { "modified": DATE_ISO8601(DATE_NOW()), "playbooks": newplaybooks }) IN @@collection
REPLACE d WITH MERGE(d, { "modified": @now, "playbooks": newplaybooks }) IN @@collection
RETURN NEW`
return db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{
"playbookID": playbookID,
"now": time.Now().UTC(),
}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.NewDocumentID(TicketCollectionName, fmt.Sprintf("%d", id)),
},
Msg: fmt.Sprintf("Removed playbook %s", playbookID),
})
}

View File

@@ -5,16 +5,17 @@ import (
"errors"
"fmt"
"log"
"time"
"github.com/arangodb/go-driver"
"github.com/google/uuid"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/time"
)
func (db *Database) TaskGet(ctx context.Context, id int64, playbookID string, taskID string) (*models.TicketWithTickets, *models.PlaybookResponse, *models.TaskWithContext, error) {
func (db *Database) TaskGet(ctx context.Context, id int64, playbookID string, taskID string) (*model.TicketWithTickets, *model.PlaybookResponse, *model.TaskWithContext, error) {
inc, err := db.TicketGet(ctx, id)
if err != nil {
return nil, nil, nil, err
@@ -30,17 +31,17 @@ func (db *Database) TaskGet(ctx context.Context, id int64, playbookID string, ta
return nil, nil, nil, errors.New("task does not exist")
}
return inc, playbook, &models.TaskWithContext{
return inc, playbook, &model.TaskWithContext{
PlaybookId: playbookID,
PlaybookName: playbook.Name,
TaskId: taskID,
Task: *task,
Task: task,
TicketId: id,
TicketName: inc.Name,
}, nil
}
func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID string, taskID string, data interface{}) (*models.TicketWithTickets, error) {
func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID string, taskID string, data interface{}) (*model.TicketWithTickets, error) {
inc, err := db.TicketGet(ctx, id)
if err != nil {
return nil, err
@@ -65,19 +66,19 @@ func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID strin
LET newplaybook = MERGE(playbook, {"tasks": newtasks})
LET newplaybooks = MERGE(d.playbooks, { @playbookID: newplaybook } )
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "playbooks": newplaybooks } IN @@collection
UPDATE d WITH { "modified": @now, "playbooks": newplaybooks } IN @@collection
RETURN NEW`
ticket, err := db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{
"playbookID": playbookID,
"taskID": taskID,
"data": data,
"closed": time.Now().UTC(),
"now": time.Now().UTC(),
}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.NewDocumentID(TicketCollectionName, fmt.Sprintf("%d", id)),
},
Msg: fmt.Sprintf("Completed task %s in playbook %s", taskID, playbookID),
})
if err != nil {
return nil, err
@@ -91,8 +92,8 @@ func (db *Database) TaskComplete(ctx context.Context, id int64, playbookID strin
return ticket, nil
}
func extractTicketResponse(ticket *models.TicketWithTickets) *models.TicketResponse {
return &models.TicketResponse{
func extractTicketResponse(ticket *model.TicketWithTickets) *model.TicketResponse {
return &model.TicketResponse{
Artifacts: ticket.Artifacts,
Comments: ticket.Comments,
Created: ticket.Created,
@@ -112,7 +113,7 @@ func extractTicketResponse(ticket *models.TicketWithTickets) *models.TicketRespo
}
}
func (db *Database) TaskUpdate(ctx context.Context, id int64, playbookID string, taskID string, task *models.Task) (*models.TicketWithTickets, error) {
func (db *Database) TaskUpdateOwner(ctx context.Context, id int64, playbookID string, taskID string, owner string) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
@@ -121,22 +122,59 @@ func (db *Database) TaskUpdate(ctx context.Context, id int64, playbookID string,
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
LET playbook = d.playbooks[@playbookID]
LET newtasks = MERGE(playbook.tasks, { @taskID: @task } )
LET task = playbook.tasks[@taskID]
LET newtask = MERGE(task, {"owner": @owner })
LET newtasks = MERGE(playbook.tasks, { @taskID: newtask } )
LET newplaybook = MERGE(playbook, {"tasks": newtasks})
LET newplaybooks = MERGE(d.playbooks, { @playbookID: newplaybook } )
UPDATE d WITH { "modified": DATE_ISO8601(DATE_NOW()), "playbooks": newplaybooks } IN @@collection
UPDATE d WITH { "modified": @now, "playbooks": newplaybooks } IN @@collection
RETURN NEW`
ticket, err := db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{
"playbookID": playbookID,
"taskID": taskID,
"task": task,
"owner": owner,
"now": time.Now().UTC(),
}, ticketFilterVars), &busdb.Operation{
OperationType: busdb.Update,
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.NewDocumentID(TicketCollectionName, fmt.Sprintf("%d", id)),
},
})
if err != nil {
return nil, err
}
return ticket, nil
}
func (db *Database) TaskUpdateData(ctx context.Context, id int64, playbookID string, taskID string, data map[string]interface{}) (*model.TicketWithTickets, error) {
ticketFilterQuery, ticketFilterVars, err := db.Hooks.TicketWriteFilter(ctx)
if err != nil {
return nil, err
}
query := `LET d = DOCUMENT(@@collection, @ID)
` + ticketFilterQuery + `
LET playbook = d.playbooks[@playbookID]
LET task = playbook.tasks[@taskID]
LET newtask = MERGE(task, {"data": @data })
LET newtasks = MERGE(playbook.tasks, { @taskID: newtask } )
LET newplaybook = MERGE(playbook, {"tasks": newtasks})
LET newplaybooks = MERGE(d.playbooks, { @playbookID: newplaybook } )
UPDATE d WITH { "modified": @now, "playbooks": newplaybooks } IN @@collection
RETURN NEW`
ticket, err := db.ticketGetQuery(ctx, id, query, mergeMaps(map[string]interface{}{
"playbookID": playbookID,
"taskID": taskID,
"data": data,
"now": time.Now().UTC(),
}, ticketFilterVars), &busdb.Operation{
Type: bus.DatabaseEntryUpdated,
Ids: []driver.DocumentID{
driver.NewDocumentID(TicketCollectionName, fmt.Sprintf("%d", id)),
},
Msg: fmt.Sprintf("Saved task %s in playbook %s", taskID, playbookID),
})
if err != nil {
return nil, err
@@ -151,8 +189,8 @@ func (db *Database) TaskRun(ctx context.Context, id int64, playbookID string, ta
return err
}
if task.Task.Type == models.TaskTypeAutomation {
if err := runTask(id, playbookID, taskID, &task.Task, extractTicketResponse(ticket), db); err != nil {
if task.Task.Type == model.TaskTypeAutomation {
if err := runTask(id, playbookID, taskID, task.Task, extractTicketResponse(ticket), db); err != nil {
return err
}
}
@@ -160,10 +198,10 @@ func (db *Database) TaskRun(ctx context.Context, id int64, playbookID string, ta
return nil
}
func runNextTasks(id int64, playbookID string, next map[string]string, data interface{}, ticket *models.TicketResponse, db *Database) {
func runNextTasks(id int64, playbookID string, next map[string]string, data interface{}, ticket *model.TicketResponse, db *Database) {
for nextTaskID, requirement := range next {
nextTask := ticket.Playbooks[playbookID].Tasks[nextTaskID]
if nextTask.Type == models.TaskTypeAutomation {
if nextTask.Type == model.TaskTypeAutomation {
b, err := evalRequirement(requirement, data)
if err != nil {
continue
@@ -177,10 +215,10 @@ func runNextTasks(id int64, playbookID string, next map[string]string, data inte
}
}
func runTask(ticketID int64, playbookID string, taskID string, task *models.TaskResponse, ticket *models.TicketResponse, db *Database) error {
func runTask(ticketID int64, playbookID string, taskID string, task *model.TaskResponse, ticket *model.TicketResponse, db *Database) error {
playbook := ticket.Playbooks[playbookID]
msgContext := &models.Context{Playbook: playbook, Task: task, Ticket: ticket}
origin := &models.Origin{TaskOrigin: &models.TaskOrigin{TaskId: taskID, PlaybookId: playbookID, TicketId: ticketID}}
msgContext := &model.Context{Playbook: playbook, Task: task, Ticket: ticket}
origin := &model.Origin{TaskOrigin: &model.TaskOrigin{TaskId: taskID, PlaybookId: playbookID, TicketId: ticketID}}
jobID := uuid.NewString()
return publishJobMapping(jobID, *task.Automation, msgContext, origin, task.Payload, db)
}

View File

@@ -8,11 +8,11 @@ import (
"github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toTicketType(doc *models.TicketTypeForm) *models.TicketType {
return &models.TicketType{
func toTicketType(doc *model.TicketTypeForm) *model.TicketType {
return &model.TicketType{
Name: doc.Name,
Icon: doc.Icon,
DefaultPlaybooks: doc.DefaultPlaybooks,
@@ -21,8 +21,8 @@ func toTicketType(doc *models.TicketTypeForm) *models.TicketType {
}
}
func toTicketTypeResponse(key string, doc *models.TicketType) *models.TicketTypeResponse {
return &models.TicketTypeResponse{
func toTicketTypeResponse(key string, doc *model.TicketType) *model.TicketTypeResponse {
return &model.TicketTypeResponse{
ID: key,
Name: doc.Name,
Icon: doc.Icon,
@@ -32,7 +32,7 @@ func toTicketTypeResponse(key string, doc *models.TicketType) *models.TicketType
}
}
func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *models.TicketTypeForm) (*models.TicketTypeResponse, error) {
func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *model.TicketTypeForm) (*model.TicketTypeResponse, error) {
if tickettype == nil {
return nil, errors.New("requires ticket type")
}
@@ -40,7 +40,7 @@ func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *models.Tic
return nil, errors.New("requires ticket type name")
}
var doc models.TicketType
var doc model.TicketType
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.tickettypeCollection.CreateDocument(ctx, newctx, strcase.ToKebab(tickettype.Name), toTicketType(tickettype))
@@ -51,8 +51,8 @@ func (db *Database) TicketTypeCreate(ctx context.Context, tickettype *models.Tic
return toTicketTypeResponse(meta.Key, &doc), nil
}
func (db *Database) TicketTypeGet(ctx context.Context, id string) (*models.TicketTypeResponse, error) {
var doc models.TicketType
func (db *Database) TicketTypeGet(ctx context.Context, id string) (*model.TicketTypeResponse, error) {
var doc model.TicketType
meta, err := db.tickettypeCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -61,8 +61,8 @@ func (db *Database) TicketTypeGet(ctx context.Context, id string) (*models.Ticke
return toTicketTypeResponse(meta.Key, &doc), nil
}
func (db *Database) TicketTypeUpdate(ctx context.Context, id string, tickettype *models.TicketTypeForm) (*models.TicketTypeResponse, error) {
var doc models.TicketType
func (db *Database) TicketTypeUpdate(ctx context.Context, id string, tickettype *model.TicketTypeForm) (*model.TicketTypeResponse, error) {
var doc model.TicketType
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.tickettypeCollection.ReplaceDocument(ctx, id, toTicketType(tickettype))
@@ -78,16 +78,16 @@ func (db *Database) TicketTypeDelete(ctx context.Context, id string) error {
return err
}
func (db *Database) TicketTypeList(ctx context.Context) ([]*models.TicketTypeResponse, error) {
func (db *Database) TicketTypeList(ctx context.Context) ([]*model.TicketTypeResponse, error) {
query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": TicketTypeCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.TicketTypeResponse
var docs []*model.TicketTypeResponse
for {
var doc models.TicketType
var doc model.TicketType
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break

View File

@@ -6,15 +6,14 @@ import (
"errors"
"fmt"
"math/rand"
"time"
"github.com/arangodb/go-driver"
"github.com/gin-gonic/gin"
"github.com/iancoleman/strcase"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/pointer"
"github.com/SecurityBrewery/catalyst/generated/time"
"github.com/SecurityBrewery/catalyst/role"
)
@@ -32,10 +31,10 @@ func generateKey() string {
return string(b)
}
func toUser(user *models.UserForm, sha256 *string) *models.User {
func toUser(user *model.UserForm, sha256 *string) *model.User {
roles := []string{}
roles = append(roles, role.Strings(role.Explodes(user.Roles))...)
u := &models.User{
u := &model.User{
Blocked: user.Blocked,
Roles: roles,
Sha256: sha256,
@@ -45,7 +44,7 @@ func toUser(user *models.UserForm, sha256 *string) *models.User {
// log.Println(u)
// b, _ := json.Marshal(u)
// loader := gojsonschema.NewBytesLoader(b)
// res, err := models.UserSchema.Validate(loader)
// res, err := model.UserSchema.Validate(loader)
// if err != nil {
// log.Println(err)
// }
@@ -54,8 +53,8 @@ func toUser(user *models.UserForm, sha256 *string) *models.User {
return u
}
func toUserResponse(key string, user *models.User) *models.UserResponse {
return &models.UserResponse{
func toUserResponse(key string, user *model.User) *model.UserResponse {
return &model.UserResponse{
ID: key,
Roles: user.Roles,
Blocked: user.Blocked,
@@ -63,8 +62,8 @@ func toUserResponse(key string, user *models.User) *models.UserResponse {
}
}
func toNewUserResponse(key string, user *models.User, secret *string) *models.NewUserResponse {
return &models.NewUserResponse{
func toNewUserResponse(key string, user *model.User, secret *string) *model.NewUserResponse {
return &model.NewUserResponse{
ID: key,
Roles: user.Roles,
Secret: secret,
@@ -72,19 +71,19 @@ func toNewUserResponse(key string, user *models.User, secret *string) *models.Ne
}
}
func (db *Database) UserGetOrCreate(ctx *gin.Context, newUser *models.UserForm) (*models.UserResponse, error) {
func (db *Database) UserGetOrCreate(ctx context.Context, newUser *model.UserForm) (*model.UserResponse, error) {
user, err := db.UserGet(ctx, newUser.ID)
if err != nil {
newUser, err := db.UserCreate(ctx, newUser)
if err != nil {
return nil, err
}
return &models.UserResponse{ID: newUser.ID, Roles: newUser.Roles, Blocked: newUser.Blocked}, nil
return &model.UserResponse{ID: newUser.ID, Roles: newUser.Roles, Blocked: newUser.Blocked}, nil
}
return user, nil
}
func (db *Database) UserCreate(ctx context.Context, newUser *models.UserForm) (*models.NewUserResponse, error) {
func (db *Database) UserCreate(ctx context.Context, newUser *model.UserForm) (*model.NewUserResponse, error) {
var key string
var hash *string
if newUser.Apikey {
@@ -92,7 +91,7 @@ func (db *Database) UserCreate(ctx context.Context, newUser *models.UserForm) (*
hash = pointer.String(fmt.Sprintf("%x", sha256.Sum256([]byte(key))))
}
var doc models.User
var doc model.User
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.userCollection.CreateDocument(ctx, newctx, strcase.ToKebab(newUser.ID), toUser(newUser, hash))
if err != nil {
@@ -102,8 +101,8 @@ func (db *Database) UserCreate(ctx context.Context, newUser *models.UserForm) (*
return toNewUserResponse(meta.Key, &doc, pointer.String(key)), nil
}
func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*models.UserResponse, error) {
newUser := &models.UserForm{
func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*model.UserResponse, error) {
newUser := &model.UserForm{
ID: "setup",
Roles: []string{role.Admin},
Apikey: true,
@@ -111,7 +110,7 @@ func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*mod
}
hash := pointer.String(fmt.Sprintf("%x", sha256.Sum256([]byte(key))))
var doc models.User
var doc model.User
newctx := driver.WithReturnNew(ctx, &doc)
meta, err := db.userCollection.CreateDocument(ctx, newctx, strcase.ToKebab(newUser.ID), toUser(newUser, hash))
if err != nil {
@@ -121,8 +120,8 @@ func (db *Database) UserCreateSetupAPIKey(ctx context.Context, key string) (*mod
return toUserResponse(meta.Key, &doc), nil
}
func (db *Database) UserGet(ctx context.Context, id string) (*models.UserResponse, error) {
var doc models.User
func (db *Database) UserGet(ctx context.Context, id string) (*model.UserResponse, error) {
var doc model.User
meta, err := db.userCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -136,16 +135,16 @@ func (db *Database) UserDelete(ctx context.Context, id string) error {
return err
}
func (db *Database) UserList(ctx context.Context) ([]*models.UserResponse, error) {
func (db *Database) UserList(ctx context.Context) ([]*model.UserResponse, error) {
query := "FOR d IN @@collection RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*models.UserResponse
var docs []*model.UserResponse
for {
var doc models.User
var doc model.User
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break
@@ -159,7 +158,7 @@ func (db *Database) UserList(ctx context.Context) ([]*models.UserResponse, error
return docs, err
}
func (db *Database) UserByHash(ctx context.Context, sha256 string) (*models.UserResponse, error) {
func (db *Database) UserByHash(ctx context.Context, sha256 string) (*model.UserResponse, error) {
query := `FOR d in @@collection
FILTER d.sha256 == @sha256
RETURN d`
@@ -170,7 +169,7 @@ func (db *Database) UserByHash(ctx context.Context, sha256 string) (*models.User
}
defer cursor.Close()
var doc models.User
var doc model.User
meta, err := cursor.ReadDocument(ctx, &doc)
if err != nil {
return nil, err
@@ -179,8 +178,8 @@ func (db *Database) UserByHash(ctx context.Context, sha256 string) (*models.User
return toUserResponse(meta.Key, &doc), err
}
func (db *Database) UserUpdate(ctx context.Context, id string, user *models.UserForm) (*models.UserResponse, error) {
var doc models.User
func (db *Database) UserUpdate(ctx context.Context, id string, user *model.UserForm) (*model.UserResponse, error) {
var doc model.User
_, err := db.userCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
@@ -192,6 +191,8 @@ func (db *Database) UserUpdate(ctx context.Context, id string, user *models.User
ctx = driver.WithReturnNew(ctx, &doc)
user.ID = id
meta, err := db.userCollection.ReplaceDocument(ctx, id, toUser(user, nil))
if err != nil {
return nil, err

85
database/userdata.go Normal file
View File

@@ -0,0 +1,85 @@
package database
import (
"context"
"errors"
"github.com/arangodb/go-driver"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/model"
)
func toUserDataResponse(key string, doc *model.UserData) *model.UserDataResponse {
return &model.UserDataResponse{
Email: doc.Email,
ID: key,
Image: doc.Image,
Name: doc.Name,
Timeformat: doc.Timeformat,
}
}
func (db *Database) UserDataCreate(ctx context.Context, id string, userdata *model.UserData) error {
if userdata == nil {
return errors.New("requires setting")
}
if id == "" {
return errors.New("requires username")
}
_, err := db.userdataCollection.CreateDocument(ctx, ctx, id, userdata)
return err
}
func (db *Database) UserDataGetOrCreate(ctx context.Context, id string, newUserData *model.UserData) (*model.UserDataResponse, error) {
setting, err := db.UserDataGet(ctx, id)
if err != nil {
return toUserDataResponse(id, newUserData), db.UserDataCreate(ctx, id, newUserData)
}
return setting, nil
}
func (db *Database) UserDataGet(ctx context.Context, id string) (*model.UserDataResponse, error) {
var doc model.UserData
meta, err := db.userdataCollection.ReadDocument(ctx, id, &doc)
if err != nil {
return nil, err
}
return toUserDataResponse(meta.Key, &doc), err
}
func (db *Database) UserDataList(ctx context.Context) ([]*model.UserDataResponse, error) {
query := "FOR d IN @@collection SORT d.username ASC RETURN d"
cursor, _, err := db.Query(ctx, query, map[string]interface{}{"@collection": UserDataCollectionName}, busdb.ReadOperation)
if err != nil {
return nil, err
}
defer cursor.Close()
var docs []*model.UserDataResponse
for {
var doc model.UserData
meta, err := cursor.ReadDocument(ctx, &doc)
if driver.IsNoMoreDocuments(err) {
break
} else if err != nil {
return nil, err
}
docs = append(docs, toUserDataResponse(meta.Key, &doc))
}
return docs, err
}
func (db *Database) UserDataUpdate(ctx context.Context, id string, userdata *model.UserData) (*model.UserDataResponse, error) {
var doc model.UserData
ctx = driver.WithReturnNew(ctx, &doc)
meta, err := db.userdataCollection.ReplaceDocument(ctx, id, userdata)
if err != nil {
return nil, err
}
return toUserDataResponse(meta.Key, &doc), nil
}

View File

@@ -3,24 +3,19 @@ package database_test
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/pointer"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/generated/pointer"
"github.com/SecurityBrewery/catalyst/test"
)
func init() {
gin.SetMode(gin.TestMode)
}
var bob = &models.UserData{
var bob = &model.UserData{
Email: pointer.String("bob@example.org"),
Name: pointer.String("Bob"),
}
var bobResponse = &models.UserDataResponse{
var bobResponse = &model.UserDataResponse{
ID: "bob",
Email: pointer.String("bob@example.org"),
Name: pointer.String("Bob"),
@@ -29,7 +24,7 @@ var bobResponse = &models.UserDataResponse{
func TestDatabase_UserDataCreate(t *testing.T) {
type args struct {
id string
setting *models.UserData
setting *model.UserData
}
tests := []struct {
name string
@@ -63,7 +58,7 @@ func TestDatabase_UserDataGet(t *testing.T) {
tests := []struct {
name string
args args
want *models.UserDataResponse
want *model.UserDataResponse
wantErr bool
}{
{name: "Normal get", args: args{id: "bob"}, want: bobResponse},
@@ -98,10 +93,10 @@ func TestDatabase_UserDataGet(t *testing.T) {
func TestDatabase_UserDataList(t *testing.T) {
tests := []struct {
name string
want []*models.UserDataResponse
want []*model.UserDataResponse
wantErr bool
}{
{name: "Normal list", want: []*models.UserDataResponse{bobResponse}},
{name: "Normal list", want: []*model.UserDataResponse{bobResponse}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -129,7 +124,7 @@ func TestDatabase_UserDataList(t *testing.T) {
func TestDatabase_UserDataUpdate(t *testing.T) {
type args struct {
id string
setting *models.UserData
setting *model.UserData
}
tests := []struct {
name string

View File

@@ -10,6 +10,7 @@ definitions:
properties:
name: { type: string, example: "2.2.2.2" }
type: { type: string }
kind: { type: string }
status: { type: string, example: "Unknown" }
enrichments: { type: object, additionalProperties: { $ref: "#/definitions/Enrichment" } }

View File

@@ -22,11 +22,6 @@ paths:
script: ""
type: [ global, artifact, playbook ]
schema: "{\"title\":\"Input\",\"type\":\"object\",\"properties\":{\"default\":{\"type\":\"string\",\"title\":\"Value\"}},\"required\":[\"default\"]}"
- id: thehive
image: "docker.io/python:3"
script: ""
type: [ global ]
schema: "{\"title\":\"TheHive credentials\",\"type\":\"object\",\"properties\":{\"thehiveurl\":{\"type\":\"string\",\"title\":\"TheHive URL (e.g. 'https://thehive.example.org')\"},\"thehivekey\":{\"type\":\"string\",\"title\":\"TheHive API Key\"},\"skip_files\":{\"type\":\"boolean\", \"default\": true, \"title\":\"Skip Files (much faster)\"},\"keep_ids\":{\"type\":\"boolean\", \"default\": true, \"title\":\"Keep IDs and overwrite existing IDs\"}},\"required\":[\"thehiveurl\", \"thehivekey\", \"skip_files\", \"keep_ids\"]}"
- id: vt.hash
image: "docker.io/python:3"
script: ""

167
definition/dashboards.yaml Normal file
View File

@@ -0,0 +1,167 @@
swagger: "2.0"
info: { version: "", title: "" }
paths:
/statistics:
get:
tags: [ "statistics" ]
summary: "Get statistics"
operationId: "getStatistics"
responses:
"200":
description: "successful operation"
schema: { $ref: '#/definitions/Statistics' }
examples:
test:
unassigned: 0
open_tickets_per_user: { }
tickets_per_week: { "2021-39": 3 }
tickets_per_type: { "alert": 2, "incident": 1 }
security: [ { roles: [ "ticket:read" ] } ]
/dashboards:
get:
tags: [ "dashboards" ]
summary: "List dashboards"
operationId: "listDashboards"
responses:
"200":
description: "successful operation"
schema: { type: array, items: { $ref: "#/definitions/DashboardResponse" } }
examples:
test:
- id: simple
name: Simple
widgets:
- name: "open_tickets_per_user"
aggregation: "owner"
filter: 'status == "open"'
type: "bar"
width: 4
- name: "tickets_per_week"
aggregation: 'CONCAT(DATE_YEAR(created), "-", DATE_ISOWEEK(created) < 10 ? "0" : "", DATE_ISOWEEK(created))'
type: "line"
width: 8
security: [ { roles: [ "dashboard:read" ] } ]
post:
tags: [ "dashboards" ]
summary: "Create a new dashboard"
operationId: "createDashboard"
parameters:
- { name: "template", in: "body", description: "New template", required: true, schema: { $ref: "#/definitions/Dashboard" }, x-example: { name: "My Dashboard", widgets: [ ] } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/DashboardResponse" }
examples:
test:
id: "my-dashboard"
name: "My Dashboard"
widgets: []
security: [ { roles: [ "dashboard:write" ] } ]
/dashboards/{id}:
get:
tags: [ "dashboards" ]
summary: "Get a single dashboard"
operationId: "getDashboard"
parameters:
- { name: "id", in: "path", description: "Dashboard ID", required: true, type: string, x-example: "simple" }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/DashboardResponse" }
examples:
test:
id: simple
name: Simple
widgets:
- name: "open_tickets_per_user"
aggregation: "owner"
filter: 'status == "open"'
type: "bar"
width: 4
- name: "tickets_per_week"
aggregation: 'CONCAT(DATE_YEAR(created), "-", DATE_ISOWEEK(created) < 10 ? "0" : "", DATE_ISOWEEK(created))'
type: "line"
width: 8
security: [ { roles: [ "dashboard:read" ] } ]
put:
tags: [ "dashboards" ]
summary: "Update an existing dashboard"
operationId: "updateDashboard"
parameters:
- { name: "id", in: "path", description: "Dashboard ID", required: true, type: string, x-example: "simple" }
- { name: "dashboard", in: "body", description: "Dashboard object that needs to be added", required: true, schema: { $ref: "#/definitions/Dashboard" }, x-example: { name: "Simple", widgets: [] } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/DashboardResponse" }
examples:
test:
id: simple
name: Simple
widgets: []
security: [ { roles: [ "dashboard:write" ] } ]
delete:
tags: [ "dashboards" ]
summary: "Delete a dashboard"
operationId: "deleteDashboard"
parameters:
- { name: "id", in: "path", description: "Dashboard ID", required: true, type: string, x-example: "simple" }
responses:
"204": { description: "successful operation" }
security: [ { roles: [ "dashboard:write" ] } ]
/dashboard/data:
get:
tags: [ "dashboards" ]
summary: "Get widget data"
operationId: "dashboardData"
parameters:
- { name: "aggregation", in: "query", description: "Aggregation", required: true, type: string, x-example: "type" }
- { name: "filter", in: "query", description: "Filter", type: string, x-example: 'status == "closed"' }
responses:
"200":
description: "successful operation"
schema: { type: object }
examples:
test:
alert: 2
incident: 1
security: [ { roles: [ "dashboard:read" ] } ]
definitions:
Statistics:
type: object
required: [ unassigned, open_tickets_per_user, tickets_per_week, tickets_per_type ]
properties:
unassigned: { type: integer }
open_tickets_per_user: { type: object, additionalProperties: { type: integer } }
tickets_per_week: { type: object, additionalProperties: { type: integer } }
tickets_per_type: { type: object, additionalProperties: { type: integer } }
Dashboard:
type: object
required: [ name, widgets ]
properties:
name: { type: string }
widgets: { type: array, items: { $ref: "#/definitions/Widget" } }
DashboardResponse:
type: object
required: [ id, name, widgets ]
properties:
id: { type: string }
name: { type: string }
widgets: { type: array, items: { $ref: "#/definitions/Widget" } }
Widget:
type: object
required: [ name, type, aggregation, width ]
properties:
name: { type: string }
type: { type: string, enum: [ "bar", "line", "pie" ] }
filter: { type: string }
aggregation: { type: string }
width: { type: integer, minimum: 1, maximum: 12 }

View File

@@ -13,7 +13,7 @@ paths:
schema: { type: array, items: { $ref: "#/definitions/JobResponse" } }
examples:
test:
- id: "99cd67131b48"
- id: "b81c2366-ea37-43d2-b61b-03afdc21d985"
automation: "hash.sha1"
payload: "test"
status: "created"
@@ -23,9 +23,13 @@ paths:
summary: "Start a new job"
operationId: "runJob"
parameters:
- { name: "job", in: "body", description: "New job", required: true, schema: { $ref: "#/definitions/JobForm" }, x-example: { automation: "hash.sha1", message: { payload: "test" } } }
- { name: "job", in: "body", description: "New job", required: true, schema: { $ref: "#/definitions/JobForm" }, x-example: { automation: "hash.sha1", payload: "test" } }
responses:
"204": { description: "successful operation" }
"200":
description: "successful operation"
schema: { $ref: "#/definitions/JobResponse" }
examples:
test: { id: "87390749-2125-4a87-91c5-da7e3f9bebf1", automation: "hash.sha1", payload: "test", status: "created" }
security: [ { roles: [ "job:write" ] } ]
/jobs/{id}:
@@ -34,27 +38,27 @@ paths:
summary: "Get a single job"
operationId: "getJob"
parameters:
- { name: "id", in: "path", description: "Job ID", required: true, type: string, x-example: "99cd67131b48" }
- { name: "id", in: "path", description: "Job ID", required: true, type: string, x-example: "b81c2366-ea37-43d2-b61b-03afdc21d985" }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/JobResponse" }
examples:
test: { id: "99cd67131b48", automation: "hash.sha1", payload: "test", status: "created" }
test: { id: "b81c2366-ea37-43d2-b61b-03afdc21d985", automation: "hash.sha1", payload: "test", status: "created" }
security: [ { roles: [ "job:read" ] } ]
put:
tags: [ "jobs" ]
summary: "Update an existing job"
operationId: "updateJob"
parameters:
- { name: "id", in: "path", description: "Job ID", required: true, type: string, x-example: "99cd67131b48" }
- { name: "job", in: "body", description: "Job object that needs to be added", required: true, schema: { $ref: "#/definitions/Job" }, x-example: { id: "99cd67131b48", automation: "hash.sha1", payload: "test", status: "failed" } }
- { name: "id", in: "path", description: "Job ID", required: true, type: string, x-example: "b81c2366-ea37-43d2-b61b-03afdc21d985" }
- { name: "job", in: "body", description: "Job object that needs to be added", required: true, schema: { $ref: "#/definitions/JobUpdate" }, x-example: { status: "failed", running: false } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/JobResponse" }
examples:
test: { id: "99cd67131b48", automation: "hash.sha1", payload: "test", status: "failed" }
test: { id: "b81c2366-ea37-43d2-b61b-03afdc21d985", automation: "hash.sha1", payload: "test", status: "failed" }
security: [ { roles: [ "job:write" ] } ]
@@ -62,7 +66,7 @@ definitions:
Message:
type: object
properties:
payload: { type: object }
payload: { }
secrets: { type: object, additionalProperties: { type: string } }
context: { $ref: "#/definitions/Context" }
@@ -103,6 +107,16 @@ definitions:
payload: { }
origin: { $ref: "#/definitions/Origin" }
JobUpdate:
type: object
required: [ running, status ]
properties:
container: { type: string }
running: { type: boolean }
status: { type: string }
log: { type: string }
output: { type: object }
Job:
type: object
required: [ automation, running, status ]

View File

@@ -16,14 +16,15 @@ paths:
schema: { type: array, items: { $ref: "#/definitions/LogEntry" } }
examples:
test:
- { "created": "2021-10-02T18:05:00.333535+02:00","creator": "bob","reference": "tickets/294511","message": "Fail run account resist lend solve incident centre priority temperature. Cause change distribution examine location technique shape partner milk customer. Rail tea plate soil report cook railway interpretation breath action. Exercise dream accept park conclusion addition shoot assistance may answer. Gold writer link stop combine hear power name commitment operation. Determine lifespan support grow degree henry exclude detail set religion. Direct library policy convention chain retain discover ride walk student. Gather proposal select march aspect play noise avoid encourage employ. Assessment preserve transport combine wish influence income guess run stand. Charge limit crime ignore statement foundation study issue stop claim." }
- { type: "manual", "created": "2021-12-12T12:12:12.000000012Z","creator": "bob","reference": "tickets/294511","message": "Fail run account resist lend solve incident centre priority temperature. Cause change distribution examine location technique shape partner milk customer. Rail tea plate soil report cook railway interpretation breath action. Exercise dream accept park conclusion addition shoot assistance may answer. Gold writer link stop combine hear power name commitment operation. Determine lifespan support grow degree henry exclude detail set religion. Direct library policy convention chain retain discover ride walk student. Gather proposal select march aspect play noise avoid encourage employ. Assessment preserve transport combine wish influence income guess run stand. Charge limit crime ignore statement foundation study issue stop claim." }
security: [ { roles: [ "log:read" ] } ]
definitions:
LogEntry:
type: object
required: [ reference, creator, created, message ]
required: [ type, reference, creator, created, message ]
properties:
type: { type: string }
reference: { type: string }
creator: { type: string }
created: { type: string, format: "date-time" }

View File

@@ -32,7 +32,7 @@ paths:
responses:
"200":
description: "successful operation"
schema: { type: array, items: { $ref: "#/definitions/PlaybookTemplateResponse" } }
schema: { $ref: "#/definitions/PlaybookTemplateResponse" }
examples:
test:
id: simple-2

View File

@@ -10,7 +10,7 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/Settings" }
schema: { $ref: "#/definitions/SettingsResponse" }
examples:
test:
version: "0.0.0-test"
@@ -21,31 +21,81 @@ paths:
- { icon: "mdi-radioactive", id: "incident", name: "Incidents", default_template: "default", default_playbooks: [ ] }
- { icon: "mdi-fingerprint", id: "investigation", name: "Forensic Investigations", default_template: "default", default_playbooks: [ ] }
- { icon: "mdi-target", id: "hunt", name: "Threat Hunting", default_template: "default", default_playbooks: [ ] }
artifactKinds:
- { icon: "mdi-server", id: "asset", name: "Asset" }
- { icon: "mdi-bullseye", id: "ioc", name: "IOC" }
artifactStates:
- { icon: "mdi-help-circle-outline", id: "unknown", name: "Unknown", color: "info" }
- { icon: "mdi-skull", id: "malicious", name: "Malicious", color: "error" }
- { icon: "mdi-check", id: "clean", name: "Clean", color: "success" }
roles: [
"admin:backup:read", "admin:backup:restore", "admin:group:write", "admin:job:read", "admin:job:write",
"admin:log:read", "admin:ticket:delete", "admin:user:write", "admin:userdata:read",
"admin:userdata:write", "analyst:automation:read",
"analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read",
"analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read",
"analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write",
"analyst:tickettype:read", "analyst:user:read", "engineer:automation:write",
"engineer:playbook:write", "engineer:rule:write", "engineer:template:write",
"engineer:tickettype:write" ]
"admin:backup:read", "admin:backup:restore", "admin:dashboard:write", "admin:group:write", "admin:job:read", "admin:job:write",
"admin:log:read", "admin:settings:write", "admin:ticket:delete", "admin:user:write", "admin:userdata:read",
"admin:userdata:write", "analyst:automation:read",
"analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read",
"analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read",
"analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write",
"analyst:tickettype:read", "analyst:user:read", "engineer:automation:write",
"engineer:playbook:write", "engineer:rule:write", "engineer:template:write",
"engineer:tickettype:write" ]
security: [ { roles: [ "settings:read" ] } ]
post:
tags: [ "settings" ]
summary: "Save settings"
operationId: "saveSettings"
parameters:
- { name: "settings", in: "body", description: "Save settings", required: true, schema: { $ref: "#/definitions/Settings" }, x-example: { timeformat: "YYYY-MM-DDThh:mm:ss", artifactKinds: [ { icon: "mdi-server", id: "asset", name: "Asset" }, { icon: "mdi-bullseye", id: "ioc", name: "IOC" } ], artifactStates: [ { icon: "mdi-help-circle-outline", id: "unknown", name: "Unknown", color: "info" },{ icon: "mdi-skull", id: "malicious", name: "Malicious", color: "error" },{ icon: "mdi-check", id: "clean", name: "Clean", color: "success" } ] } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/SettingsResponse" }
examples:
test:
version: "0.0.0-test"
tier: community
timeformat: "YYYY-MM-DDThh:mm:ss"
ticketTypes:
- { icon: "mdi-alert", id: "alert", name: "Alerts", default_template: "default", default_playbooks: [ ] }
- { icon: "mdi-radioactive", id: "incident", name: "Incidents", default_template: "default", default_playbooks: [ ] }
- { icon: "mdi-fingerprint", id: "investigation", name: "Forensic Investigations", default_template: "default", default_playbooks: [ ] }
- { icon: "mdi-target", id: "hunt", name: "Threat Hunting", default_template: "default", default_playbooks: [ ] }
artifactKinds:
- { icon: "mdi-server", id: "asset", name: "Asset" }
- { icon: "mdi-bullseye", id: "ioc", name: "IOC" }
artifactStates:
- { icon: "mdi-help-circle-outline", id: "unknown", name: "Unknown", color: "info" }
- { icon: "mdi-skull", id: "malicious", name: "Malicious", color: "error" }
- { icon: "mdi-check", id: "clean", name: "Clean", color: "success" }
roles: [
"admin:backup:read", "admin:backup:restore", "admin:dashboard:write", "admin:group:write", "admin:job:read", "admin:job:write",
"admin:log:read", "admin:settings:write", "admin:ticket:delete", "admin:user:write", "admin:userdata:read",
"admin:userdata:write", "analyst:automation:read",
"analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read",
"analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read",
"analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write",
"analyst:tickettype:read", "analyst:user:read", "engineer:automation:write",
"engineer:playbook:write", "engineer:rule:write", "engineer:template:write",
"engineer:tickettype:write" ]
security: [ { roles: [ "settings:write" ] } ]
definitions:
Settings:
type: object
required: [ version, tier, timeformat, ticketTypes, artifactStates ]
required: [ timeformat, artifactKinds, artifactStates ]
properties:
timeformat: { title: "Time Format", type: string }
artifactKinds: { title: "Artifact Kinds", type: array, items: { $ref: "#/definitions/Type" } }
artifactStates: { title: "Artifact States", type: array, items: { $ref: "#/definitions/Type" } }
SettingsResponse:
type: object
required: [ version, tier, timeformat, ticketTypes, artifactKinds, artifactStates ]
properties:
version: { title: "Version", type: string }
tier: { title: "Tier", type: string, enum: [ "community", "enterprise" ] }
timeformat: { title: "Time Format", type: string }
ticketTypes: { title: "Ticket Types", type: array, items: { $ref: "#/definitions/TicketTypeResponse" } }
artifactKinds: { title: "Artifact Kinds", type: array, items: { $ref: "#/definitions/Type" } }
artifactStates: { title: "Artifact States", type: array, items: { $ref: "#/definitions/Type" } }
roles: { title: "Roles", type: array, items: { type: string } }

View File

@@ -1,31 +0,0 @@
swagger: "2.0"
info: { version: "", title: "" }
paths:
/statistics:
get:
tags: [ "statistics" ]
summary: "Get statistics"
operationId: "getStatistics"
responses:
"200":
description: "successful operation"
schema: { $ref: '#/definitions/Statistics' }
examples:
test:
unassigned: 0
open_tickets_per_user: { }
tickets_per_week: { "2021-39": 3 }
tickets_per_type: { "alert": 2, "incident": 1 }
security: [ { roles: [ "ticket:read" ] } ]
definitions:
Statistics:
type: object
required: [ unassigned, open_tickets_per_user, tickets_per_week, tickets_per_type ]
properties:
unassigned: { type: integer }
open_tickets_per_user: { type: object, additionalProperties: { type: integer } }
tickets_per_week: { type: object, additionalProperties: { type: integer } }
tickets_per_type: { type: object, additionalProperties: { type: integer } }

View File

@@ -10,37 +10,12 @@ paths:
responses:
"200":
description: "successful operation"
schema: { type: array, items: { $ref: "#/definitions/TaskResponse" } }
schema: { type: array, items: { $ref: "#/definitions/TaskWithContext" } }
examples:
test: [ ]
security: [ { roles: [ "ticket:read" ] } ]
definitions:
TaskForm:
type: object
required: [ name, type ]
properties:
name: { type: string, example: "Inform user" }
type: { type: string, enum: [ task, input, automation ], example: "task" }
done: { type: boolean }
owner: { type: string }
data: { type: object }
# automation
automation: { type: string }
payload: { type: object, additionalProperties: { type: string } }
# input
schema: { type: object }
# workflow
join: { type: boolean, example: false }
next: { type: object, additionalProperties: { type: string } }
created: { type: string, format: "date-time", example: "1985-04-12T23:20:50.52Z" }
closed: { type: string, format: "date-time", example: "1985-04-12T23:20:50.52Z" }
Task:
type: object
required: [ name, type, done, created ]

View File

@@ -23,21 +23,21 @@ paths:
count: 3
tickets:
- id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-10-02T16:04:59.078206Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -49,8 +49,8 @@ paths:
- { name: "94d5cab6f5fe3422a447ab15436e7a672bc0c09a", status: "unknown" }
- { name: "http://www.customerviral.io/scalable/vertical/killer", status: "clean" }
- { name: "leadreintermediate.io", status: "malicious" }
- { id: 8125, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00",name: "phishing from selenafadel@von.com detected", owner: "demo", references: [ { href: "https://www.seniorleading-edge.name/users/efficient", name: "recovery" },{ href: "http://www.dynamicseamless.com/clicks-and-mortar", name: "force" },{ href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8125, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z",name: "phishing from selenafadel@von.com detected", owner: "demo", references: [ { href: "https://www.seniorleading-edge.name/users/efficient", name: "recovery" },{ href: "http://www.dynamicseamless.com/clicks-and-mortar", name: "force" },{ href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:read" ] } ]
post:
tags: [ "tickets" ]
@@ -68,8 +68,8 @@ paths:
name: "Wannacry infection"
type: "incident"
status: "open"
created: "1985-04-12T23:20:50.52Z"
modified: "1985-04-12T23:20:50.52Z"
created: "2021-12-12T12:12:12.000000012Z"
modified: "2021-12-12T12:12:12.000000012Z"
owner: "bob"
schema: "{}"
security: [ { roles: [ "ticket:write" ] } ]
@@ -80,7 +80,7 @@ paths:
summary: "Create a new tickets in batch"
operationId: "createTicketBatch"
parameters:
- { name: "ticket", in: "body", description: "New ticket", required: true, schema: { type: array, items: { $ref: "#/definitions/TicketForm" } }, x-example: [ { id: 123, owner: bob, name: "Wannacry infection", status: "open", type: "incident" } ] }
- { name: "ticket", in: "body", description: "New ticket", required: true, schema: { $ref: "#/definitions/TicketFormArray" }, x-example: [ { id: 123, owner: bob, name: "Wannacry infection", status: "open", type: "incident" } ] }
responses:
"204": { description: "successful operation" }
security: [ { roles: [ "ticket:write" ] } ]
@@ -95,12 +95,12 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-10-02T16:04:59.078186Z"
name: "phishing from selenafadel@von.com detected"
owner: "demo"
references:
@@ -114,7 +114,7 @@ paths:
status: "closed"
type: "alert"
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:read" ] } ]
put:
tags: [ "tickets" ]
@@ -122,16 +122,16 @@ paths:
operationId: "updateTicket"
parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8125 }
- { name: "ticket", in: "body", description: "Updated ticket", required: true, schema: { $ref: "#/definitions/Ticket" }, x-example: { "created": "2021-10-02T18:04:59.078186+02:00",modified: "2021-10-02T18:04:59.078186+02:00", name: "phishing from selenafadel@von.org detected", owner: "demo", references: [ { href: "https://www.seniorleading-edge.name/users/efficient", name: "recovery" },{ href: "http://www.dynamicseamless.com/clicks-and-mortar", name: "force" },{ href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ], schema: "{}", status: "closed", type: "alert" } }
- { name: "ticket", in: "body", description: "Updated ticket", required: true, schema: { $ref: "#/definitions/Ticket" }, x-example: { "created": "2021-12-12T12:12:12.000000012Z",modified: "2021-12-12T12:12:12.000000012Z", name: "phishing from selenafadel@von.org detected", owner: "demo", references: [ { href: "https://www.seniorleading-edge.name/users/efficient", name: "recovery" },{ href: "http://www.dynamicseamless.com/clicks-and-mortar", name: "force" },{ href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ], schema: "{}", status: "closed", type: "alert" } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-12-12T12:12:12.000000012Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "phishing from selenafadel@von.org detected"
owner: "demo"
references:
@@ -145,7 +145,7 @@ paths:
status: "closed"
type: "alert"
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:write" ] } ]
delete:
tags: [ "tickets" ]
@@ -168,12 +168,12 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8126
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-10-02T16:04:59.078186Z"
name: "Surfaceintroduce virus detected"
owner: "demo"
references:
@@ -185,21 +185,21 @@ paths:
type: "alert"
tickets:
- id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-10-02T16:04:59.078206Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -212,8 +212,8 @@ paths:
- { name: "http://www.customerviral.io/scalable/vertical/killer", status: "clean" }
- { name: "leadreintermediate.io", status: "malicious" }
- id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-10-02T16:04:59.078186Z"
name: "phishing from selenafadel@von.com detected"
owner: "demo"
references:
@@ -234,12 +234,12 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8126
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-10-02T16:04:59.078186Z"
name: "Surfaceintroduce virus detected"
owner: "demo"
references:
@@ -262,16 +262,16 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "phishing from selenafadel@von.com detected"
owner: "demo"
comments:
- created: "2021-10-02T18:04:59.078186+02:00"
- created: "2021-12-12T12:12:12.000000012Z"
creator: "bob"
message: "My first comment"
references:
@@ -282,7 +282,7 @@ paths:
status: "closed"
type: "alert"
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/comments/{commentID}:
@@ -297,25 +297,25 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -336,16 +336,16 @@ paths:
operationId: "setReferences"
parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8125 }
- { name: "references", in: "body", description: "All ticket references", required: true, schema: { type: array, items: { $ref: "#/definitions/Reference" } }, x-example: [ { href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ] }
- { name: "references", in: "body", description: "All ticket references", required: true, schema: { $ref: "#/definitions/ReferenceArray" }, x-example: [ { href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ] }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "phishing from selenafadel@von.com detected"
owner: "demo"
references: [ { href: "http://www.leadscalable.biz/envisioneer", name: "fund" } ]
@@ -353,7 +353,7 @@ paths:
status: "closed"
type: "alert"
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/schema:
@@ -363,16 +363,16 @@ paths:
operationId: "setSchema"
parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8125 }
- { name: "schema", in: "body", description: "New ticket schema", schema: { type: string }, x-example: "{}" }
- { name: "schema", in: "body", description: "New ticket schema", required: true, schema: { type: string }, x-example: "{}" }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-10-02T16:04:59.078186Z"
name: "phishing from selenafadel@von.com detected"
owner: "demo"
references:
@@ -383,40 +383,7 @@ paths:
status: "closed"
type: "alert"
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/files:
put:
tags: [ "tickets" ]
summary: "Link files to an ticket"
description: "Link files to an ticket. The files themself will be stored in object storage."
operationId: "linkFiles"
parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8125 }
- { name: "files", in: "body", description: "Added files", required: true, schema: { type: array, items: { $ref: "#/definitions/File" } }, x-example: [ { key: myfile, name: "document.doc" } ] }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
examples:
test:
id: 8125
created: "2021-10-02T18:04:59.078186+02:00"
modified: "2021-10-02T18:04:59.078186+02:00"
name: "phishing from selenafadel@von.com detected"
owner: "demo"
references:
- { href: "https://www.seniorleading-edge.name/users/efficient", name: "recovery" }
- { href: "http://www.dynamicseamless.com/clicks-and-mortar", name: "force" }
- { href: "http://www.leadscalable.biz/envisioneer", name: "fund" }
"schema": "{}"
status: "closed"
type: "alert"
files: [ { key: myfile, name: "document.doc" } ]
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/playbooks:
@@ -430,7 +397,7 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8125
@@ -438,11 +405,11 @@ paths:
owner: demo
type: "alert"
status: "closed"
created: "1985-04-12T23:20:50.52Z"
modified: "1985-04-12T23:20:50.52Z"
created: "2021-10-02T16:04:59.078186Z"
modified: "2021-12-12T12:12:12.000000012Z"
schema: "{}"
tickets:
- { id: 8126, created: "2021-10-02T18:04:59.078186+02:00", modified: "2021-10-02T18:04:59.078186+02:00", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
- { id: 8126, created: "2021-10-02T16:04:59.078186Z", modified: "2021-10-02T16:04:59.078186Z", name: "Surfaceintroduce virus detected", owner: "demo", references: [ { href: "http://www.centralworld-class.io/synthesize", name: "university" },{ href: "https://www.futurevirtual.org/supply-chains/markets/sticky/iterate", name: "goal" },{ href: "http://www.chiefsyndicate.io/action-items", name: "unemployment" } ],"schema": "{}", status: "closed", type: "alert" }
references:
- { href: "https://www.seniorleading-edge.name/users/efficient", name: recovery }
- { href: "http://www.dynamicseamless.com/clicks-and-mortar", name: force }
@@ -454,7 +421,7 @@ paths:
input:
active: true
done: false
created: "2021-10-02T18:04:59.078186+02:00"
created: "2021-12-12T12:12:12.000000012Z"
order: 0
name: Upload malware if possible
type: input
@@ -472,7 +439,7 @@ paths:
hash:
active: false
done: false
created: "2021-10-02T18:04:59.078186+02:00"
created: "2021-12-12T12:12:12.000000012Z"
order: 1
name: Hash the malware
type: automation
@@ -485,10 +452,11 @@ paths:
escalate:
active: false
done: false
created: "2021-10-02T18:04:59.078186+02:00"
created: "2021-12-12T12:12:12.000000012Z"
order: 2
name: Escalate to malware team
type: task
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/playbooks/{playbookID}:
delete:
@@ -501,15 +469,15 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
name: "live zebra"
type: "incident"
status: "closed"
created: "1985-04-12T23:20:50.52Z"
modified: "1985-04-12T23:20:50.52Z"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
owner: "demo"
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: performance }
@@ -615,35 +583,80 @@ paths:
/tickets/{id}/playbooks/{playbookID}/task/{taskID}:
put:
tags: [ "tickets" ]
summary: "Set a ticket playbook task"
operationId: "setTask"
summary: "Set a ticket playbook task data"
operationId: "setTaskData"
parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8123 }
- { name: "playbookID", in: "path", description: "Playbook ID", required: true, type: string, x-example: "phishing" }
- { name: "taskID", in: "path", description: "Task ID", required: true, type: string, x-example: "board" }
- { name: "task", in: "body", description: "Task", required: true, schema: { $ref: "#/definitions/Task" }, x-example: { done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input", data: { boardInvolved: true } } }
- { name: "data", in: "body", description: "Task data", required: true, schema: { type: object }, x-example: { boardInvolved: true } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input", data: { boardInvolved: true } }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input", data: { boardInvolved: true } }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
- { href: "https://www.corporateintuitive.org/intuitive/platforms/integrate", name: "suggest" }
"schema": "{\n \"definitions\": {},\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"https://example.com/object1618746510.json\",\n \"title\": \"Event\",\n \"type\": \"object\",\n \"required\": [\n \"severity\",\n \"description\",\n \"tlp\"\n ],\n \"properties\": {\n \"severity\": {\n \"$id\": \"#root/severity\",\n \"title\": \"Severity\",\n \"type\": \"string\",\n \"default\": \"Medium\",\n \"nx-enum\": [\n \"Low\",\n \"Medium\",\n \"High\"\n ],\n \"x-cols\": 6,\n \"x-class\": \"pr-2\",\n \"x-display\": \"icon\",\n \"x-itemIcon\": \"icon\",\n \"oneOf\": [\n {\n \"const\": \"Low\",\n \"title\": \"Low\",\n \"icon\": \"mdi-chevron-up\"\n },\n {\n \"const\": \"Medium\",\n \"title\": \"Medium\",\n \"icon\": \"mdi-chevron-double-up\"\n },\n {\n \"const\": \"High\",\n \"title\": \"High\",\n \"icon\": \"mdi-chevron-triple-up\"\n }\n ]\n },\n \"tlp\": {\n \"$id\": \"#root/tlp\",\n \"title\": \"TLP\",\n \"type\": \"string\",\n \"nx-enum\": [\n \"White\",\n \"Green\",\n \"Amber\",\n \"Red\"\n ],\n \"x-cols\": 6,\n \"x-class\": \"pr-2\",\n \"x-display\": \"icon\",\n \"x-itemIcon\": \"icon\",\n \"oneOf\": [\n {\n \"const\": \"White\",\n \"title\": \"White\",\n \"icon\": \"mdi-alpha-w\"\n },\n {\n \"const\": \"Green\",\n \"title\": \"Green\",\n \"icon\": \"mdi-alpha-g\"\n },\n {\n \"const\": \"Amber\",\n \"title\": \"Amber\",\n \"icon\": \"mdi-alpha-a\"\n },\n {\n \"const\": \"Red\",\n \"title\": \"Red\",\n \"icon\": \"mdi-alpha-r\"\n }\n ]\n },\n \"description\": {\n \"$id\": \"#root/description\",\n \"title\": \"Description\",\n \"type\": \"string\",\n \"x-display\": \"textarea\",\n \"x-class\": \"pr-2\"\n }\n }\n}\n"
status: "closed"
type: "incident"
artifacts:
- { name: "94d5cab6f5fe3422a447ab15436e7a672bc0c09a", status: "unknown" }
- { name: "http://www.customerviral.io/scalable/vertical/killer", status: "clean" }
- { name: "leadreintermediate.io", status: "malicious" }
security: [ { roles: [ "ticket:write" ] } ]
/tickets/{id}/playbooks/{playbookID}/task/{taskID}/owner:
put:
tags: [ "tickets" ]
summary: "Set a ticket playbook task owner"
operationId: "setTaskOwner"
parameters:
- { name: "id", in: "path", description: "Ticket ID", required: true, type: integer, format: "int64", x-example: 8123 }
- { name: "playbookID", in: "path", description: "Playbook ID", required: true, type: string, x-example: "phishing" }
- { name: "taskID", in: "path", description: "Task ID", required: true, type: string, x-example: "board" }
- { name: "owner", in: "body", description: "Task owner", required: true, schema: { type: string }, x-example: "eve" }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input", owner: "eve" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -670,25 +683,25 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", closed: "2021-10-02T18:04:59.078186+02:00", done: true, "active": false, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input", data: { boardInvolved: true } }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", closed: "2021-12-12T12:12:12.000000012Z", done: true, "active": false, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input", data: { boardInvolved: true } }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -726,25 +739,25 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -785,25 +798,25 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-10-02T16:04:59.078206Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -826,25 +839,25 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/TicketResponse" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-12-12T12:12:12.000000012Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -882,25 +895,25 @@ paths:
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/Artifact" }
schema: { $ref: "#/definitions/TicketWithTickets" }
examples:
test:
id: 8123
created: "2021-10-02T18:04:59.078206+02:00"
modified: "2021-10-02T18:04:59.078206+02:00"
created: "2021-10-02T16:04:59.078206Z"
modified: "2021-10-02T16:04:59.078206Z"
name: "live zebra"
owner: "demo"
playbooks:
phishing:
name: "Phishing"
tasks:
"block-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-10-02T18:04:59.078186+02:00", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
"block-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 6, name: "Block IOCs", type: "task" }
"block-sender": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 3, name: "Block sender","next": { "extract-iocs": "" }, type: "task" }
"board": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": true, "order": 0, name: "Board Involvement?","next": { "escalate": "boardInvolved == true","mail-available": "boardInvolved == false" },"schema": { "properties": { "boardInvolved": { "default": false, "title": "A board member is involved.", type: "boolean" } }, "required": [ "boardInvolved" ], "title": "Board Involvement?", type: "object" }, type: "input" }
"escalate": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 1, name: "Escalate to CISO", type: "task" }
"extract-iocs": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 5, name: "Extract IOCs", "next": { "block-iocs": "" },"schema": { "properties": { "iocs": { "items": { type: "string" },"title": "IOCs", type: "array" } }, "title": "Extract IOCs", type: "object" }, type: "input" }
"mail-available": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 2, name: "Mail available","next": { "block-sender": "schemaKey == 'yes'", "extract-iocs": "schemaKey == 'yes'", "search-email-gateway": "schemaKey == 'no'" },"schema": { "oneOf": [ { "properties": { "mail": { "title": "Mail", type: "string", "x-display": "textarea" }, "schemaKey": { "const": "yes", type: "string" } },"required": [ "mail" ], "title": "Yes" },{ "properties": { "schemaKey": { "const": "no", type: "string" } },"title": "No" } ],"title": "Mail available", type: "object" }, type: "input" }
"search-email-gateway": { created: "2021-12-12T12:12:12.000000012Z", done: false, "active": false, "order": 4, name: "Search email gateway","next": { "extract-iocs": "" }, type: "task" }
references:
- { href: "https://www.leadmaximize.net/e-services/back-end", name: "performance" }
- { href: "http://www.corporateinteractive.name/rich", name: "autumn" }
@@ -911,10 +924,13 @@ paths:
artifacts:
- { name: "94d5cab6f5fe3422a447ab15436e7a672bc0c09a", status: "unknown" }
- { name: "http://www.customerviral.io/scalable/vertical/killer", status: "clean" }
- { name: "leadreintermediate.io", status: "malicious", enrichments: { hash.sha1: { name: "hash.sha1", created: "2021-10-03T18:44:06.488923+02:00", data: { "hash": "b7a067a742c20d07a7456646de89bc2d408a1153" } } } }
- { name: "leadreintermediate.io", status: "malicious", enrichments: { hash.sha1: { name: "hash.sha1", created: "2021-12-12T12:12:12.000000012Z", data: { "hash": "b7a067a742c20d07a7456646de89bc2d408a1153" } } } }
security: [ { roles: [ "ticket:write" ] } ]
definitions:
TicketFormArray:
type: array
items: { $ref: "#/definitions/TicketForm" }
TicketForm:
type: object
@@ -1037,6 +1053,8 @@ definitions:
comments: { type: array, items: { $ref: '#/definitions/Comment' } }
artifacts: { type: array, items: { $ref: "#/definitions/Artifact" } }
logs: { type: array, items: { $ref: '#/definitions/LogEntry' } }
created: { type: string, format: "date-time", example: "1985-04-12T23:20:50.52Z" }
modified: { type: string, format: "date-time", example: "1985-04-12T23:20:50.52Z" }
@@ -1065,6 +1083,10 @@ definitions:
created: { type: string, format: "date-time" }
message: { type: string }
ReferenceArray:
type: array
items: { $ref: '#/definitions/Reference' }
Reference:
type: object
required: [ name, href ]

View File

@@ -12,7 +12,7 @@ paths:
description: "successful operation"
schema: { $ref: "#/definitions/UserResponse" }
examples:
test: { id: bob, roles: [ "admin:backup:read", "admin:backup:restore", "admin:group:write", "admin:job:read", "admin:job:write", "admin:log:read", "admin:ticket:delete", "admin:user:write", "admin:userdata:read", "admin:userdata:write", "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], blocked: false, apikey: false }
test: { id: bob, roles: [ "admin:backup:read", "admin:backup:restore", "admin:dashboard:write", "admin:group:write", "admin:job:read", "admin:job:write", "admin:log:read", "admin:settings:write", "admin:ticket:delete", "admin:user:write", "admin:userdata:read", "admin:userdata:write", "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read","analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], blocked: false, apikey: false }
security: [ { roles: [ "currentuser:read" ] } ]
/users:
@@ -26,21 +26,21 @@ paths:
schema: { type: array, items: { $ref: "#/definitions/UserResponse" } }
examples:
test:
- { id: bob, blocked: false, roles: [ "admin:backup:read", "admin:backup:restore", "admin:group:write", "admin:job:read", "admin:job:write", "admin:log:read", "admin:ticket:delete", "admin:user:write", "admin:userdata:read", "admin:userdata:write", "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], apikey: false }
- { id: script, roles: [ "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], blocked: false, apikey: true }
- { id: bob, blocked: false, roles: [ "admin:backup:read", "admin:backup:restore", "admin:dashboard:write", "admin:group:write", "admin:job:read", "admin:job:write", "admin:log:read", "admin:settings:write", "admin:ticket:delete", "admin:user:write", "admin:userdata:read", "admin:userdata:write", "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], apikey: false }
- { id: script, roles: [ "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], blocked: false, apikey: true }
security: [ { roles: [ "user:read" ] } ]
post:
tags: [ "users" ]
summary: "Create user"
operationId: "createUser"
parameters:
- { name: "user", in: "body", description: "user object that needs to be added", required: true, schema: { $ref: "#/definitions/UserForm" }, x-example: { id: "syncscript", roles: [ "analyst" ] } }
- { name: "user", in: "body", description: "user object that needs to be added", required: true, schema: { $ref: "#/definitions/UserForm" }, x-example: { id: "syncscript", roles: [ "analyst" ], blocked: false, apikey: true } }
responses:
"200":
description: "successful operation"
schema: { $ref: "#/definitions/NewUserResponse" }
examples:
test: { id: "syncscript", roles: [ "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read" ], secret: "v39bOuobnlEljfWzjAgoKzhmnh1xSMxH", blocked: false }
test: { id: "syncscript", roles: [ "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read" ], secret: "v39bOuobnlEljfWzjAgoKzhmnh1xSMxH", blocked: false }
security: [ { roles: [ "user:write" ] } ]
/users/{id}:
get:
@@ -54,7 +54,7 @@ paths:
description: "successful operation"
schema: { $ref: "#/definitions/UserResponse" }
examples:
test: { id: "script", roles: [ "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], blocked: false, apikey: true }
test: { id: "script", roles: [ "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ], blocked: false, apikey: true }
security: [ { roles: [ "user:read" ] } ]
put:
tags: [ "users" ]
@@ -62,7 +62,7 @@ paths:
operationId: "updateUser"
parameters:
- { name: "id", in: "path", description: "Template ID", required: true, type: string, x-example: "bob" }
- { name: "user", in: "body", description: "user object that needs to be added", required: true, schema: { $ref: "#/definitions/UserForm" }, x-example: { roles: [ "analyst", "admin" ] } }
- { name: "user", in: "body", description: "user object that needs to be added", required: true, schema: { $ref: "#/definitions/UserForm" }, x-example: { id: "syncscript", roles: [ "analyst", "admin" ], blocked: false, apikey: false } }
responses:
"200":
description: "successful operation"
@@ -70,7 +70,7 @@ paths:
examples:
test:
id: bob
roles: [ "admin:backup:read", "admin:backup:restore", "admin:group:write", "admin:job:read", "admin:job:write", "admin:log:read", "admin:ticket:delete", "admin:user:write", "admin:userdata:read", "admin:userdata:write", "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ]
roles: [ "admin:backup:read", "admin:backup:restore", "admin:dashboard:write", "admin:group:write", "admin:job:read", "admin:job:write", "admin:log:read", "admin:settings:write", "admin:ticket:delete", "admin:user:write", "admin:userdata:read", "admin:userdata:write", "analyst:automation:read", "analyst:currentsettings:write", "analyst:currentuser:read", "analyst:currentuserdata:read", "analyst:dashboard:read", "analyst:file", "analyst:group:read", "analyst:playbook:read", "analyst:rule:read", "analyst:settings:read", "analyst:template:read", "analyst:ticket:read", "analyst:ticket:write", "analyst:tickettype:read", "analyst:user:read", "engineer:automation:write", "engineer:playbook:write", "engineer:rule:write", "engineer:template:write", "engineer:tickettype:write" ]
apikey: false
blocked: false
security: [ { roles: [ "user:write" ] } ]

View File

@@ -1,35 +1,40 @@
version: '2.2'
version: '2.4'
services:
nginx:
image: nginx:1.21
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
ports: [ "80:80", "8529:8529", "9000:9000", "9001:9001", "9002:9002" ]
ports: [ "80:80", "8529:8529", "9000:9000", "9001:9001", "9002:9002", "9003:9003" ]
networks: [ catalyst ]
arangodb:
image: arangodb/arangodb:3.8.1
environment:
ARANGO_ROOT_PASSWORD: foobar
networks: [ catalyst ]
emitter:
image: emitter/server
environment:
- EMITTER_LICENSE=PfA8ID8izeSlDUlNZgNXo77DQV9QzlNtxTk64WreCXKfDZsREAVXUXwh20UKOZdkALbLTmOytO_iC6mc_twKAQ:3
# A9RysEsPJni8RaHeg_K0FKXQNfBrUyw-
networks: [ catalyst ]
minio:
image: minio/minio
image: minio/minio:RELEASE.2021-12-10T23-03-39Z
environment:
MINIO_ROOT_USER: minio
MINIO_ROOT_PASSWORD: minio123
command: server /data -console-address ":9003"
networks: [ catalyst ]
postgres:
image: postgres
image: postgres:13
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: password
networks: [ catalyst ]
keycloak:
image: quay.io/keycloak/keycloak:14.0.0
@@ -47,3 +52,8 @@ services:
volumes:
- ./keycloak/realm.json:/tmp/realm.json
depends_on: [ postgres ]
networks: [ catalyst ]
networks:
catalyst:
name: catalyst

View File

@@ -53,6 +53,17 @@ http {
server_name _;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_connect_timeout 300;
# Default is HTTP/1, keepalive is only enabled in HTTP/1.1
proxy_http_version 1.1;
proxy_set_header Connection "";
chunked_transfer_encoding off;
resolver 127.0.0.11 valid=30s;
set $upstream_minio minio;
proxy_pass http://$upstream_minio:9000;
@@ -76,6 +87,28 @@ http {
proxy_set_header X-Forwarded-Server $host;
}
}
server {
listen 9003 default_server;
server_name _;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_connect_timeout 300;
# Default is HTTP/1, keepalive is only enabled in HTTP/1.1
proxy_http_version 1.1;
proxy_set_header Connection "";
chunked_transfer_encoding off;
resolver 127.0.0.11 valid=30s;
set $upstream_minio minio;
proxy_pass http://$upstream_minio:9003;
}
}
}
stream {

138
file.go
View File

@@ -1,32 +1,40 @@
package catalyst
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"strconv"
"github.com/arangodb/go-driver"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/gin-gonic/gin"
"github.com/go-chi/chi"
tusd "github.com/tus/tusd/pkg/handler"
"github.com/tus/tusd/pkg/s3store"
"github.com/SecurityBrewery/catalyst/bus"
"github.com/SecurityBrewery/catalyst/database"
"github.com/SecurityBrewery/catalyst/database/busdb"
"github.com/SecurityBrewery/catalyst/generated/api"
"github.com/SecurityBrewery/catalyst/generated/model"
"github.com/SecurityBrewery/catalyst/storage"
)
func upload(client *s3.S3, external string) gin.HandlerFunc {
return func(ctx *gin.Context) {
ticketID, exists := ctx.Params.Get("ticketID")
if !exists {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "ticketID not given"})
func tusdUpload(db *database.Database, bus *bus.Bus, client *s3.S3, external string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ticketID := chi.URLParam(r, "ticketID")
if ticketID == "" {
api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("ticketID not given"))
return
}
if err := storage.CreateBucket(client, ticketID); err != nil {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("could not create bucket: %w", err)})
api.JSONErrorStatus(w, http.StatusBadRequest, fmt.Errorf("could not create bucket: %w", err))
return
}
@@ -36,43 +44,120 @@ func upload(client *s3.S3, external string) gin.HandlerFunc {
store.UseIn(composer)
handler, err := tusd.NewUnroutedHandler(tusd.Config{
BasePath: external + "/api/files/" + ticketID + "/upload/",
StoreComposer: composer,
BasePath: external + "/api/files/" + ticketID + "/tusd/",
StoreComposer: composer,
NotifyCompleteUploads: true,
})
if err != nil {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("could not create tusd handler: %w", err)})
api.JSONErrorStatus(w, http.StatusBadRequest, fmt.Errorf("could not create tusd handler: %w", err))
return
}
switch ctx.Request.Method {
userID := "unknown"
user, ok := busdb.UserFromContext(r.Context())
if ok {
userID = user.ID
}
go func() {
event := <-handler.CompleteUploads
id, err := strconv.ParseInt(ticketID, 10, 64)
if err != nil {
return
}
file := &model.File{Key: event.Upload.Storage["Key"], Name: event.Upload.MetaData["filename"]}
ctx := context.Background()
doc, err := db.AddFile(ctx, id, file)
if err != nil {
log.Println(err)
return
}
err = bus.PublishRequest(userID, "LinkFiles", []driver.DocumentID{driver.DocumentID(fmt.Sprintf("tickets/%d", doc.ID))})
if err != nil {
log.Println(err)
}
}()
switch r.Method {
case http.MethodHead:
gin.WrapF(handler.HeadFile)(ctx)
handler.HeadFile(w, r)
case http.MethodPost:
gin.WrapF(handler.PostFile)(ctx)
handler.PostFile(w, r)
case http.MethodPatch:
gin.WrapF(handler.PatchFile)(ctx)
handler.PatchFile(w, r)
default:
log.Println(errors.New("unknown method"))
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "unknown method"})
api.JSONErrorStatus(w, http.StatusInternalServerError, errors.New("unknown method"))
}
}
}
func upload(db *database.Database, client *s3.S3, uploader *s3manager.Uploader) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ticketID := chi.URLParam(r, "ticketID")
if ticketID == "" {
api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("ticketID not given"))
return
}
file, header, err := r.FormFile("file")
if err != nil {
api.JSONErrorStatus(w, http.StatusBadRequest, err)
return
}
defer file.Close()
if err := storage.CreateBucket(client, ticketID); err != nil {
api.JSONErrorStatus(w, http.StatusBadRequest, fmt.Errorf("could not create bucket: %w", err))
return
}
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String("catalyst-" + ticketID),
Key: aws.String(header.Filename),
Body: file,
})
if err != nil {
api.JSONErrorStatus(w, http.StatusBadRequest, err)
return
}
id, err := strconv.ParseInt(ticketID, 10, 64)
if err != nil {
api.JSONErrorStatus(w, http.StatusBadRequest, err)
return
}
_, err = db.AddFile(r.Context(), id, &model.File{
Key: header.Filename,
Name: header.Filename,
})
if err != nil {
api.JSONErrorStatus(w, http.StatusBadRequest, err)
return
}
}
}
func download(downloader *s3manager.Downloader) gin.HandlerFunc {
return func(ctx *gin.Context) {
ticketID, exists := ctx.Params.Get("ticketID")
if !exists {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "ticketID not given"})
func download(downloader *s3manager.Downloader) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ticketID := chi.URLParam(r, "ticketID")
if ticketID == "" {
api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("ticketID not given"))
return
}
key, exists := ctx.Params.Get("key")
if !exists {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "key not given"})
key := chi.URLParam(r, "key")
if key == "" {
api.JSONErrorStatus(w, http.StatusBadRequest, errors.New("key not given"))
return
}
buf := sequentialWriter{ctx.Writer}
buf := sequentialWriter{w}
downloader.Concurrency = 1
_, err := downloader.Download(buf, &s3.GetObjectInput{
@@ -80,8 +165,7 @@ func download(downloader *s3manager.Downloader) gin.HandlerFunc {
Key: aws.String(key),
})
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err})
return
api.JSONErrorStatus(w, http.StatusInternalServerError, err)
}
}
}

View File

@@ -18,11 +18,9 @@ mv generated/openapi.json generated/community.json
openapi-generator generate -i generated/catalyst.yml -o generated -g openapi
mv generated/openapi.json generated/catalyst.json
# generate python client
# openapi-generator generate -i generated/community.yml -o generated/python -g python --package-name catalystpy --ignore-file-override .openapi-generator-ignore
echo generate server and tests
go run ./generator/. ./generator
swagger-go-chi generated/community.yml generated
rm -rf generated/auth generated/cli
echo generate typescript client
openapi-generator generate -i generated/catalyst.yml -o ui/src/client -g typescript-axios --artifact-version 1.0.0-SNAPSHOT
@@ -30,8 +28,7 @@ openapi-generator generate -i generated/catalyst.yml -o ui/src/client -g typescr
rm -rf gen
rm -rf generated/models/old
rm -rf generated/.openapi-generator generated/.openapi-generator-ignore generated/README.md
# rm -rf generated/python/.openapi-generator generated/python/.gitlab-ci.yml generated/python/git_push.sh generated/python/.travis.yml generated/python/.gitignore generated/python/.openapi-generator-ignore
rm -rf ui/src/client/.openapi-generator ui/src/client/git_push.sh ui/src/client/.gitignore ui/src/client/.openapi-generator-ignore
go mod tidy
gci -w -local "github.com/SecurityBrewery/catalyst" .
gci write --Section Standard --Section Default --Section "Prefix(github.com/SecurityBrewery/catalyst)" .

192
generated/api/api.go Executable file
View File

@@ -0,0 +1,192 @@
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/xeipuuv/gojsonschema"
)
type HTTPError struct {
Status int
Internal error
}
func (e *HTTPError) Error() string {
return fmt.Sprintf("HTTPError(%d): %s", e.Status, e.Internal)
}
func (e *HTTPError) Unwrap() error {
return e.Internal
}
func parseURLInt64(r *http.Request, s string) (int64, error) {
i, err := strconv.ParseInt(chi.URLParam(r, s), 10, 64)
if err != nil {
return 0, fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
return i, nil
}
func parseURLInt(r *http.Request, s string) (int, error) {
i, err := strconv.Atoi(chi.URLParam(r, s))
if err != nil {
return 0, fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
return i, nil
}
func parseQueryInt(r *http.Request, s string) (int, error) {
i, err := strconv.Atoi(r.URL.Query().Get(s))
if err != nil {
return 0, fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
return i, nil
}
func parseQueryBool(r *http.Request, s string) (bool, error) {
b, err := strconv.ParseBool(r.URL.Query().Get(s))
if err != nil {
return false, fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
return b, nil
}
func parseQueryStringArray(r *http.Request, key string) ([]string, error) {
stringArray, ok := r.URL.Query()[key]
if !ok {
return nil, nil
}
return removeEmpty(stringArray), nil
}
func removeEmpty(l []string) []string {
var stringArray []string
for _, s := range l {
if s == "" {
continue
}
stringArray = append(stringArray, s)
}
return stringArray
}
func parseQueryBoolArray(r *http.Request, key string) ([]bool, error) {
stringArray, ok := r.URL.Query()[key]
if !ok {
return nil, nil
}
var boolArray []bool
for _, s := range stringArray {
if s == "" {
continue
}
b, err := strconv.ParseBool(s)
if err != nil {
return nil, fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
boolArray = append(boolArray, b)
}
return boolArray, nil
}
func parseQueryOptionalInt(r *http.Request, key string) (*int, error) {
s := r.URL.Query().Get(key)
if s == "" {
return nil, nil
}
i, err := strconv.Atoi(s)
if err != nil {
return nil, fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
return &i, nil
}
func parseQueryOptionalStringArray(r *http.Request, key string) ([]string, error) {
return parseQueryStringArray(r, key)
}
func parseQueryOptionalBoolArray(r *http.Request, key string) ([]bool, error) {
return parseQueryBoolArray(r, key)
}
func parseBody(b []byte, i interface{}) error {
dec := json.NewDecoder(bytes.NewBuffer(b))
err := dec.Decode(i)
if err != nil {
return fmt.Errorf("%w", &HTTPError{http.StatusUnprocessableEntity, err})
}
return nil
}
func JSONError(w http.ResponseWriter, err error) {
JSONErrorStatus(w, http.StatusInternalServerError, err)
}
func JSONErrorStatus(w http.ResponseWriter, status int, err error) {
w.WriteHeader(status)
b, _ := json.Marshal(map[string]string{"error": err.Error()})
w.Write(b)
}
func response(w http.ResponseWriter, v interface{}, err error) {
if err != nil {
var httpError *HTTPError
if errors.As(err, &httpError) {
JSONErrorStatus(w, httpError.Status, httpError.Internal)
return
}
JSONError(w, err)
return
}
if v == nil {
w.WriteHeader(http.StatusNoContent)
return
}
w.WriteHeader(http.StatusOK)
b, _ := json.Marshal(v)
w.Write(b)
}
func validateSchema(body []byte, schema *gojsonschema.Schema, w http.ResponseWriter) bool {
jl := gojsonschema.NewBytesLoader(body)
validationResult, err := schema.Validate(jl)
if err != nil {
JSONError(w, err)
return true
}
if !validationResult.Valid() {
w.WriteHeader(http.StatusUnprocessableEntity)
var validationErrors []string
for _, valdiationError := range validationResult.Errors() {
validationErrors = append(validationErrors, valdiationError.String())
}
b, _ := json.Marshal(map[string]interface{}{"error": "wrong input", "errors": validationErrors})
w.Write(b)
return true
}
return false
}
func NilMiddleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
}
}
func IgnoreRoles(_ []string) func(next http.Handler) http.Handler {
return NilMiddleware()
}

1235
generated/api/server.go Executable file

File diff suppressed because it is too large Load Diff

25
generated/api/static.go Executable file
View File

@@ -0,0 +1,25 @@
package api
import (
"io/fs"
"net/http"
"net/http/httputil"
"net/url"
)
func Static(fsys fs.FS) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.FS(fsys)).ServeHTTP(w, r)
}
}
func Proxy(dest string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
u, _ := url.Parse(dest)
proxy := httputil.NewSingleHostReverseProxy(u)
r.Host = r.URL.Host
proxy.ServeHTTP(w, r)
}
}

650
generated/api/test_api.go Executable file

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
// Code generated from CAQLLexer.g4 by ANTLR 4.9.2. DO NOT EDIT.
// Code generated from CAQLLexer.g4 by ANTLR 4.9.3. DO NOT EDIT.
package parser

View File

@@ -1,4 +1,4 @@
// Code generated from CAQLParser.g4 by ANTLR 4.9.2. DO NOT EDIT.
// Code generated from CAQLParser.g4 by ANTLR 4.9.3. DO NOT EDIT.
package parser // CAQLParser
@@ -332,6 +332,9 @@ func (s *ParseContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Parse() (localctx IParseContext) {
this := p
_ = this
localctx = NewParseContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 0, CAQLParserRULE_parse)
@@ -587,6 +590,9 @@ func (p *CAQLParser) Expression() (localctx IExpressionContext) {
}
func (p *CAQLParser) expression(_p int) (localctx IExpressionContext) {
this := p
_ = this
var _parentctx antlr.ParserRuleContext = p.GetParserRuleContext()
_parentState := p.GetState()
localctx = NewExpressionContext(p, p.GetParserRuleContext(), _parentState)
@@ -1076,6 +1082,9 @@ func (s *Operator_unaryContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Operator_unary() (localctx IOperator_unaryContext) {
this := p
_ = this
localctx = NewOperator_unaryContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 4, CAQLParserRULE_operator_unary)
@@ -1264,6 +1273,9 @@ func (p *CAQLParser) Reference() (localctx IReferenceContext) {
}
func (p *CAQLParser) reference(_p int) (localctx IReferenceContext) {
this := p
_ = this
var _parentctx antlr.ParserRuleContext = p.GetParserRuleContext()
_parentState := p.GetState()
localctx = NewReferenceContext(p, p.GetParserRuleContext(), _parentState)
@@ -1469,6 +1481,9 @@ func (s *Compound_valueContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Compound_value() (localctx ICompound_valueContext) {
this := p
_ = this
localctx = NewCompound_valueContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 8, CAQLParserRULE_compound_value)
@@ -1614,6 +1629,9 @@ func (s *Function_callContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Function_call() (localctx IFunction_callContext) {
this := p
_ = this
localctx = NewFunction_callContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 10, CAQLParserRULE_function_call)
var _la int
@@ -1778,6 +1796,9 @@ func (s *Value_literalContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Value_literal() (localctx IValue_literalContext) {
this := p
_ = this
localctx = NewValue_literalContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 12, CAQLParserRULE_value_literal)
var _la int
@@ -1912,6 +1933,9 @@ func (s *ArrayContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Array() (localctx IArrayContext) {
this := p
_ = this
localctx = NewArrayContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 14, CAQLParserRULE_array)
var _la int
@@ -2087,6 +2111,9 @@ func (s *ObjectContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Object() (localctx IObjectContext) {
this := p
_ = this
localctx = NewObjectContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 16, CAQLParserRULE_object)
var _la int
@@ -2272,6 +2299,9 @@ func (s *Object_elementContext) ExitRule(listener antlr.ParseTreeListener) {
}
func (p *CAQLParser) Object_element() (localctx IObject_elementContext) {
this := p
_ = this
localctx = NewObject_elementContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 18, CAQLParserRULE_object_element)
@@ -2409,6 +2439,9 @@ func (s *Object_element_nameContext) ExitRule(listener antlr.ParseTreeListener)
}
func (p *CAQLParser) Object_element_name() (localctx IObject_element_nameContext) {
this := p
_ = this
localctx = NewObject_element_nameContext(p, p.GetParserRuleContext(), p.GetState())
p.EnterRule(localctx, 20, CAQLParserRULE_object_element_name)
var _la int
@@ -2467,6 +2500,9 @@ func (p *CAQLParser) Sempred(localctx antlr.RuleContext, ruleIndex, predIndex in
}
func (p *CAQLParser) Expression_Sempred(localctx antlr.RuleContext, predIndex int) bool {
this := p
_ = this
switch predIndex {
case 0:
return p.Precpred(p.GetParserRuleContext(), 13)
@@ -2513,6 +2549,9 @@ func (p *CAQLParser) Expression_Sempred(localctx antlr.RuleContext, predIndex in
}
func (p *CAQLParser) Reference_Sempred(localctx antlr.RuleContext, predIndex int) bool {
this := p
_ = this
switch predIndex {
case 13:
return p.Precpred(p.GetParserRuleContext(), 2)

View File

@@ -1,4 +1,4 @@
// Code generated from CAQLParser.g4 by ANTLR 4.9.2. DO NOT EDIT.
// Code generated from CAQLParser.g4 by ANTLR 4.9.3. DO NOT EDIT.
package parser // CAQLParser

View File

@@ -1,4 +1,4 @@
// Code generated from CAQLParser.g4 by ANTLR 4.9.2. DO NOT EDIT.
// Code generated from CAQLParser.g4 by ANTLR 4.9.3. DO NOT EDIT.
package parser // CAQLParser

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

669
generated/model/model.go Executable file
View File

@@ -0,0 +1,669 @@
package model
import (
"time"
"github.com/xeipuuv/gojsonschema"
)
var (
schemaLoader = gojsonschema.NewSchemaLoader()
ArtifactSchema = new(gojsonschema.Schema)
ArtifactOriginSchema = new(gojsonschema.Schema)
AutomationSchema = new(gojsonschema.Schema)
AutomationFormSchema = new(gojsonschema.Schema)
AutomationResponseSchema = new(gojsonschema.Schema)
CommentSchema = new(gojsonschema.Schema)
CommentFormSchema = new(gojsonschema.Schema)
ContextSchema = new(gojsonschema.Schema)
DashboardSchema = new(gojsonschema.Schema)
DashboardResponseSchema = new(gojsonschema.Schema)
EnrichmentSchema = new(gojsonschema.Schema)
EnrichmentFormSchema = new(gojsonschema.Schema)
FileSchema = new(gojsonschema.Schema)
JobSchema = new(gojsonschema.Schema)
JobFormSchema = new(gojsonschema.Schema)
JobResponseSchema = new(gojsonschema.Schema)
JobUpdateSchema = new(gojsonschema.Schema)
LogEntrySchema = new(gojsonschema.Schema)
MessageSchema = new(gojsonschema.Schema)
NewUserResponseSchema = new(gojsonschema.Schema)
OriginSchema = new(gojsonschema.Schema)
PlaybookSchema = new(gojsonschema.Schema)
PlaybookResponseSchema = new(gojsonschema.Schema)
PlaybookTemplateSchema = new(gojsonschema.Schema)
PlaybookTemplateFormSchema = new(gojsonschema.Schema)
PlaybookTemplateResponseSchema = new(gojsonschema.Schema)
ReferenceSchema = new(gojsonschema.Schema)
ReferenceArraySchema = new(gojsonschema.Schema)
SettingsSchema = new(gojsonschema.Schema)
SettingsResponseSchema = new(gojsonschema.Schema)
StatisticsSchema = new(gojsonschema.Schema)
TaskSchema = new(gojsonschema.Schema)
TaskOriginSchema = new(gojsonschema.Schema)
TaskResponseSchema = new(gojsonschema.Schema)
TaskWithContextSchema = new(gojsonschema.Schema)
TicketSchema = new(gojsonschema.Schema)
TicketFormSchema = new(gojsonschema.Schema)
TicketFormArraySchema = new(gojsonschema.Schema)
TicketListSchema = new(gojsonschema.Schema)
TicketResponseSchema = new(gojsonschema.Schema)
TicketSimpleResponseSchema = new(gojsonschema.Schema)
TicketTemplateSchema = new(gojsonschema.Schema)
TicketTemplateFormSchema = new(gojsonschema.Schema)
TicketTemplateResponseSchema = new(gojsonschema.Schema)
TicketTypeSchema = new(gojsonschema.Schema)
TicketTypeFormSchema = new(gojsonschema.Schema)
TicketTypeResponseSchema = new(gojsonschema.Schema)
TicketWithTicketsSchema = new(gojsonschema.Schema)
TypeSchema = new(gojsonschema.Schema)
UserSchema = new(gojsonschema.Schema)
UserDataSchema = new(gojsonschema.Schema)
UserDataResponseSchema = new(gojsonschema.Schema)
UserFormSchema = new(gojsonschema.Schema)
UserResponseSchema = new(gojsonschema.Schema)
WidgetSchema = new(gojsonschema.Schema)
)
func init() {
err := schemaLoader.AddSchemas(
gojsonschema.NewStringLoader(`{"type":"object","properties":{"enrichments":{"type":"object","additionalProperties":{"$ref":"#/definitions/Enrichment"}},"kind":{"type":"string"},"name":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"}},"required":["name"],"$id":"#/definitions/Artifact"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifact":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["ticket_id","artifact"],"$id":"#/definitions/ArtifactOrigin"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"image":{"type":"string"},"schema":{"type":"string"},"script":{"type":"string"},"type":{"items":{"type":"string","enum":["artifact","playbook","global"]},"type":"array"}},"required":["image","script","type"],"$id":"#/definitions/Automation"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"image":{"type":"string"},"schema":{"type":"string"},"script":{"type":"string"},"type":{"items":{"type":"string","enum":["artifact","playbook","global"]},"type":"array"}},"required":["id","image","script","type"],"$id":"#/definitions/AutomationForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"image":{"type":"string"},"schema":{"type":"string"},"script":{"type":"string"},"type":{"items":{"type":"string","enum":["artifact","playbook","global"]},"type":"array"}},"required":["id","image","script","type"],"$id":"#/definitions/AutomationResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"}},"required":["creator","created","message"],"$id":"#/definitions/Comment"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"}},"required":["message"],"$id":"#/definitions/CommentForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifact":{"$ref":"#/definitions/Artifact"},"playbook":{"$ref":"#/definitions/PlaybookResponse"},"task":{"$ref":"#/definitions/TaskResponse"},"ticket":{"$ref":"#/definitions/TicketResponse"}},"$id":"#/definitions/Context"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"name":{"type":"string"},"widgets":{"items":{"$ref":"#/definitions/Widget"},"type":"array"}},"required":["name","widgets"],"$id":"#/definitions/Dashboard"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"widgets":{"items":{"$ref":"#/definitions/Widget"},"type":"array"}},"required":["id","name","widgets"],"$id":"#/definitions/DashboardResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"name":{"type":"string"}},"required":["name","data","created"],"$id":"#/definitions/Enrichment"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"data":{"type":"object"},"name":{"type":"string"}},"required":["name","data"],"$id":"#/definitions/EnrichmentForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"key":{"type":"string"},"name":{"type":"string"}},"required":["key","name"],"$id":"#/definitions/File"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"automation":{"type":"string"},"container":{"type":"string"},"log":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"output":{"type":"object"},"payload":{},"running":{"type":"boolean"},"status":{"type":"string"}},"required":["automation","running","status"],"$id":"#/definitions/Job"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"automation":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"payload":{}},"required":["automation"],"$id":"#/definitions/JobForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"automation":{"type":"string"},"container":{"type":"string"},"id":{"type":"string"},"log":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"output":{"type":"object"},"payload":{},"status":{"type":"string"}},"required":["id","automation","status"],"$id":"#/definitions/JobResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"container":{"type":"string"},"log":{"type":"string"},"output":{"type":"object"},"running":{"type":"boolean"},"status":{"type":"string"}},"required":["running","status"],"$id":"#/definitions/JobUpdate"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"},"reference":{"type":"string"},"type":{"type":"string"}},"required":["type","reference","creator","created","message"],"$id":"#/definitions/LogEntry"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"context":{"$ref":"#/definitions/Context"},"payload":{},"secrets":{"type":"object","additionalProperties":{"type":"string"}}},"$id":"#/definitions/Message"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"},"secret":{"type":"string"}},"required":["id","blocked","roles"],"$id":"#/definitions/NewUserResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifact_origin":{"$ref":"#/definitions/ArtifactOrigin"},"task_origin":{"$ref":"#/definitions/TaskOrigin"}},"$id":"#/definitions/Origin"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"name":{"type":"string"},"tasks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Task"}}},"required":["name","tasks"],"$id":"#/definitions/Playbook"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"name":{"type":"string"},"tasks":{"type":"object","additionalProperties":{"$ref":"#/definitions/TaskResponse"}}},"required":["name","tasks"],"$id":"#/definitions/PlaybookResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"name":{"type":"string"},"yaml":{"type":"string"}},"required":["name","yaml"],"$id":"#/definitions/PlaybookTemplate"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"yaml":{"type":"string"}},"required":["yaml"],"$id":"#/definitions/PlaybookTemplateForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"yaml":{"type":"string"}},"required":["id","name","yaml"],"$id":"#/definitions/PlaybookTemplateResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"href":{"type":"string"},"name":{"type":"string"}},"required":["name","href"],"$id":"#/definitions/Reference"}`),
gojsonschema.NewStringLoader(`{"items":{"$ref":"#/definitions/Reference"},"type":"array","$id":"#/definitions/ReferenceArray"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifactKinds":{"title":"Artifact Kinds","items":{"$ref":"#/definitions/Type"},"type":"array"},"artifactStates":{"title":"Artifact States","items":{"$ref":"#/definitions/Type"},"type":"array"},"timeformat":{"title":"Time Format","type":"string"}},"required":["timeformat","artifactKinds","artifactStates"],"$id":"#/definitions/Settings"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifactKinds":{"title":"Artifact Kinds","items":{"$ref":"#/definitions/Type"},"type":"array"},"artifactStates":{"title":"Artifact States","items":{"$ref":"#/definitions/Type"},"type":"array"},"roles":{"title":"Roles","items":{"type":"string"},"type":"array"},"ticketTypes":{"title":"Ticket Types","items":{"$ref":"#/definitions/TicketTypeResponse"},"type":"array"},"tier":{"title":"Tier","type":"string","enum":["community","enterprise"]},"timeformat":{"title":"Time Format","type":"string"},"version":{"title":"Version","type":"string"}},"required":["version","tier","timeformat","ticketTypes","artifactKinds","artifactStates"],"$id":"#/definitions/SettingsResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"open_tickets_per_user":{"type":"object","additionalProperties":{"type":"integer"}},"tickets_per_type":{"type":"object","additionalProperties":{"type":"integer"}},"tickets_per_week":{"type":"object","additionalProperties":{"type":"integer"}},"unassigned":{"type":"integer"}},"required":["unassigned","open_tickets_per_user","tickets_per_week","tickets_per_type"],"$id":"#/definitions/Statistics"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"automation":{"type":"string"},"closed":{"format":"date-time","type":"string"},"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"done":{"type":"boolean"},"join":{"type":"boolean"},"name":{"type":"string"},"next":{"type":"object","additionalProperties":{"type":"string"}},"owner":{"type":"string"},"payload":{"type":"object","additionalProperties":{"type":"string"}},"schema":{"type":"object"},"type":{"type":"string","enum":["task","input","automation"]}},"required":["name","type","done","created"],"$id":"#/definitions/Task"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"playbook_id":{"type":"string"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"required":["ticket_id","playbook_id","task_id"],"$id":"#/definitions/TaskOrigin"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"active":{"type":"boolean"},"automation":{"type":"string"},"closed":{"format":"date-time","type":"string"},"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"done":{"type":"boolean"},"join":{"type":"boolean"},"name":{"type":"string"},"next":{"type":"object","additionalProperties":{"type":"string"}},"order":{"format":"int64","type":"number"},"owner":{"type":"string"},"payload":{"type":"object","additionalProperties":{"type":"string"}},"schema":{"type":"object"},"type":{"type":"string","enum":["task","input","automation"]}},"required":["name","type","done","created","order","active"],"$id":"#/definitions/TaskResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"playbook_id":{"type":"string"},"playbook_name":{"type":"string"},"task":{"$ref":"#/definitions/TaskResponse"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"number"},"ticket_name":{"type":"string"}},"required":["ticket_id","ticket_name","playbook_id","playbook_name","task_id","task"],"$id":"#/definitions/TaskWithContext"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Playbook"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"required":["name","type","status","created","modified","schema"],"$id":"#/definitions/Ticket"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"items":{"$ref":"#/definitions/PlaybookTemplateForm"},"type":"array"},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"required":["name","type","status"],"$id":"#/definitions/TicketForm"}`),
gojsonschema.NewStringLoader(`{"items":{"$ref":"#/definitions/TicketForm"},"type":"array","$id":"#/definitions/TicketFormArray"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"count":{"type":"number"},"tickets":{"items":{"$ref":"#/definitions/TicketSimpleResponse"},"type":"array"}},"required":["tickets","count"],"$id":"#/definitions/TicketList"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/PlaybookResponse"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"required":["id","name","type","status","created","modified","schema"],"$id":"#/definitions/TicketResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Playbook"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"required":["id","name","type","status","created","modified","schema"],"$id":"#/definitions/TicketSimpleResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"name":{"type":"string"},"schema":{"type":"string"}},"required":["name","schema"],"$id":"#/definitions/TicketTemplate"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"schema":{"type":"string"}},"required":["name","schema"],"$id":"#/definitions/TicketTemplateForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"schema":{"type":"string"}},"required":["id","name","schema"],"$id":"#/definitions/TicketTemplateResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"default_groups":{"items":{"type":"string"},"type":"array"},"default_playbooks":{"items":{"type":"string"},"type":"array"},"default_template":{"type":"string"},"icon":{"type":"string"},"name":{"type":"string"}},"required":["name","icon","default_template","default_playbooks"],"$id":"#/definitions/TicketType"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"default_groups":{"items":{"type":"string"},"type":"array"},"default_playbooks":{"items":{"type":"string"},"type":"array"},"default_template":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"}},"required":["name","icon","default_template","default_playbooks"],"$id":"#/definitions/TicketTypeForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"default_groups":{"items":{"type":"string"},"type":"array"},"default_playbooks":{"items":{"type":"string"},"type":"array"},"default_template":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"}},"required":["id","name","icon","default_template","default_playbooks"],"$id":"#/definitions/TicketTypeResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"logs":{"items":{"$ref":"#/definitions/LogEntry"},"type":"array"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/PlaybookResponse"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"tickets":{"items":{"$ref":"#/definitions/TicketSimpleResponse"},"type":"array"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"required":["id","name","type","status","created","modified","schema"],"$id":"#/definitions/TicketWithTickets"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"color":{"title":"Color","type":"string","enum":["error","info","success","warning"]},"icon":{"title":"Icon (https://materialdesignicons.com)","type":"string"},"id":{"title":"ID","type":"string"},"name":{"title":"Name","type":"string"}},"required":["id","name","icon"],"$id":"#/definitions/Type"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"apikey":{"type":"boolean"},"blocked":{"type":"boolean"},"roles":{"items":{"type":"string"},"type":"array"},"sha256":{"type":"string"}},"required":["blocked","apikey","roles"],"$id":"#/definitions/User"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"email":{"type":"string"},"image":{"type":"string"},"name":{"type":"string"},"timeformat":{"title":"Time Format (https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens)","type":"string"}},"$id":"#/definitions/UserData"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"email":{"type":"string"},"id":{"type":"string"},"image":{"type":"string"},"name":{"type":"string"},"timeformat":{"title":"Time Format (https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens)","type":"string"}},"required":["id"],"$id":"#/definitions/UserDataResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"apikey":{"type":"boolean"},"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"}},"required":["id","blocked","roles","apikey"],"$id":"#/definitions/UserForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"apikey":{"type":"boolean"},"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"}},"required":["id","blocked","roles","apikey"],"$id":"#/definitions/UserResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","properties":{"aggregation":{"type":"string"},"filter":{"type":"string"},"name":{"type":"string"},"type":{"type":"string","enum":["bar","line","pie"]},"width":{"maximum":12,"type":"integer"}},"required":["name","type","aggregation","width"],"$id":"#/definitions/Widget"}`),
)
if err != nil {
panic(err)
}
ArtifactSchema = mustCompile(`#/definitions/Artifact`)
ArtifactOriginSchema = mustCompile(`#/definitions/ArtifactOrigin`)
AutomationSchema = mustCompile(`#/definitions/Automation`)
AutomationFormSchema = mustCompile(`#/definitions/AutomationForm`)
AutomationResponseSchema = mustCompile(`#/definitions/AutomationResponse`)
CommentSchema = mustCompile(`#/definitions/Comment`)
CommentFormSchema = mustCompile(`#/definitions/CommentForm`)
ContextSchema = mustCompile(`#/definitions/Context`)
DashboardSchema = mustCompile(`#/definitions/Dashboard`)
DashboardResponseSchema = mustCompile(`#/definitions/DashboardResponse`)
EnrichmentSchema = mustCompile(`#/definitions/Enrichment`)
EnrichmentFormSchema = mustCompile(`#/definitions/EnrichmentForm`)
FileSchema = mustCompile(`#/definitions/File`)
JobSchema = mustCompile(`#/definitions/Job`)
JobFormSchema = mustCompile(`#/definitions/JobForm`)
JobResponseSchema = mustCompile(`#/definitions/JobResponse`)
JobUpdateSchema = mustCompile(`#/definitions/JobUpdate`)
LogEntrySchema = mustCompile(`#/definitions/LogEntry`)
MessageSchema = mustCompile(`#/definitions/Message`)
NewUserResponseSchema = mustCompile(`#/definitions/NewUserResponse`)
OriginSchema = mustCompile(`#/definitions/Origin`)
PlaybookSchema = mustCompile(`#/definitions/Playbook`)
PlaybookResponseSchema = mustCompile(`#/definitions/PlaybookResponse`)
PlaybookTemplateSchema = mustCompile(`#/definitions/PlaybookTemplate`)
PlaybookTemplateFormSchema = mustCompile(`#/definitions/PlaybookTemplateForm`)
PlaybookTemplateResponseSchema = mustCompile(`#/definitions/PlaybookTemplateResponse`)
ReferenceSchema = mustCompile(`#/definitions/Reference`)
ReferenceArraySchema = mustCompile(`#/definitions/ReferenceArray`)
SettingsSchema = mustCompile(`#/definitions/Settings`)
SettingsResponseSchema = mustCompile(`#/definitions/SettingsResponse`)
StatisticsSchema = mustCompile(`#/definitions/Statistics`)
TaskSchema = mustCompile(`#/definitions/Task`)
TaskOriginSchema = mustCompile(`#/definitions/TaskOrigin`)
TaskResponseSchema = mustCompile(`#/definitions/TaskResponse`)
TaskWithContextSchema = mustCompile(`#/definitions/TaskWithContext`)
TicketSchema = mustCompile(`#/definitions/Ticket`)
TicketFormSchema = mustCompile(`#/definitions/TicketForm`)
TicketFormArraySchema = mustCompile(`#/definitions/TicketFormArray`)
TicketListSchema = mustCompile(`#/definitions/TicketList`)
TicketResponseSchema = mustCompile(`#/definitions/TicketResponse`)
TicketSimpleResponseSchema = mustCompile(`#/definitions/TicketSimpleResponse`)
TicketTemplateSchema = mustCompile(`#/definitions/TicketTemplate`)
TicketTemplateFormSchema = mustCompile(`#/definitions/TicketTemplateForm`)
TicketTemplateResponseSchema = mustCompile(`#/definitions/TicketTemplateResponse`)
TicketTypeSchema = mustCompile(`#/definitions/TicketType`)
TicketTypeFormSchema = mustCompile(`#/definitions/TicketTypeForm`)
TicketTypeResponseSchema = mustCompile(`#/definitions/TicketTypeResponse`)
TicketWithTicketsSchema = mustCompile(`#/definitions/TicketWithTickets`)
TypeSchema = mustCompile(`#/definitions/Type`)
UserSchema = mustCompile(`#/definitions/User`)
UserDataSchema = mustCompile(`#/definitions/UserData`)
UserDataResponseSchema = mustCompile(`#/definitions/UserDataResponse`)
UserFormSchema = mustCompile(`#/definitions/UserForm`)
UserResponseSchema = mustCompile(`#/definitions/UserResponse`)
WidgetSchema = mustCompile(`#/definitions/Widget`)
}
type Artifact struct {
Enrichments map[string]*Enrichment `json:"enrichments,omitempty"`
Kind *string `json:"kind,omitempty"`
Name string `json:"name"`
Status *string `json:"status,omitempty"`
Type *string `json:"type,omitempty"`
}
type ArtifactOrigin struct {
Artifact string `json:"artifact"`
TicketId int64 `json:"ticket_id"`
}
type Automation struct {
Image string `json:"image"`
Schema *string `json:"schema,omitempty"`
Script string `json:"script"`
Type []string `json:"type"`
}
type AutomationForm struct {
ID string `json:"id"`
Image string `json:"image"`
Schema *string `json:"schema,omitempty"`
Script string `json:"script"`
Type []string `json:"type"`
}
type AutomationResponse struct {
ID string `json:"id"`
Image string `json:"image"`
Schema *string `json:"schema,omitempty"`
Script string `json:"script"`
Type []string `json:"type"`
}
type Comment struct {
Created time.Time `json:"created"`
Creator string `json:"creator"`
Message string `json:"message"`
}
type CommentForm struct {
Created *time.Time `json:"created,omitempty"`
Creator *string `json:"creator,omitempty"`
Message string `json:"message"`
}
type Context struct {
Artifact *Artifact `json:"artifact,omitempty"`
Playbook *PlaybookResponse `json:"playbook,omitempty"`
Task *TaskResponse `json:"task,omitempty"`
Ticket *TicketResponse `json:"ticket,omitempty"`
}
type Dashboard struct {
Name string `json:"name"`
Widgets []*Widget `json:"widgets"`
}
type DashboardResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Widgets []*Widget `json:"widgets"`
}
type Enrichment struct {
Created time.Time `json:"created"`
Data map[string]interface{} `json:"data"`
Name string `json:"name"`
}
type EnrichmentForm struct {
Data map[string]interface{} `json:"data"`
Name string `json:"name"`
}
type File struct {
Key string `json:"key"`
Name string `json:"name"`
}
type Job struct {
Automation string `json:"automation"`
Container *string `json:"container,omitempty"`
Log *string `json:"log,omitempty"`
Origin *Origin `json:"origin,omitempty"`
Output map[string]interface{} `json:"output,omitempty"`
Payload interface{} `json:"payload,omitempty"`
Running bool `json:"running"`
Status string `json:"status"`
}
type JobForm struct {
Automation string `json:"automation"`
Origin *Origin `json:"origin,omitempty"`
Payload interface{} `json:"payload,omitempty"`
}
type JobResponse struct {
Automation string `json:"automation"`
Container *string `json:"container,omitempty"`
ID string `json:"id"`
Log *string `json:"log,omitempty"`
Origin *Origin `json:"origin,omitempty"`
Output map[string]interface{} `json:"output,omitempty"`
Payload interface{} `json:"payload,omitempty"`
Status string `json:"status"`
}
type JobUpdate struct {
Container *string `json:"container,omitempty"`
Log *string `json:"log,omitempty"`
Output map[string]interface{} `json:"output,omitempty"`
Running bool `json:"running"`
Status string `json:"status"`
}
type LogEntry struct {
Created time.Time `json:"created"`
Creator string `json:"creator"`
Message string `json:"message"`
Reference string `json:"reference"`
Type string `json:"type"`
}
type Message struct {
Context *Context `json:"context,omitempty"`
Payload interface{} `json:"payload,omitempty"`
Secrets map[string]string `json:"secrets,omitempty"`
}
type NewUserResponse struct {
Blocked bool `json:"blocked"`
ID string `json:"id"`
Roles []string `json:"roles"`
Secret *string `json:"secret,omitempty"`
}
type Origin struct {
ArtifactOrigin *ArtifactOrigin `json:"artifact_origin,omitempty"`
TaskOrigin *TaskOrigin `json:"task_origin,omitempty"`
}
type Playbook struct {
Name string `json:"name"`
Tasks map[string]*Task `json:"tasks"`
}
type PlaybookResponse struct {
Name string `json:"name"`
Tasks map[string]*TaskResponse `json:"tasks"`
}
type PlaybookTemplate struct {
Name string `json:"name"`
Yaml string `json:"yaml"`
}
type PlaybookTemplateForm struct {
ID *string `json:"id,omitempty"`
Yaml string `json:"yaml"`
}
type PlaybookTemplateResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Yaml string `json:"yaml"`
}
type Reference struct {
Href string `json:"href"`
Name string `json:"name"`
}
type ReferenceArray []*Reference
type Settings struct {
ArtifactKinds []*Type `json:"artifactKinds"`
ArtifactStates []*Type `json:"artifactStates"`
Timeformat string `json:"timeformat"`
}
type SettingsResponse struct {
ArtifactKinds []*Type `json:"artifactKinds"`
ArtifactStates []*Type `json:"artifactStates"`
Roles []string `json:"roles,omitempty"`
TicketTypes []*TicketTypeResponse `json:"ticketTypes"`
Tier string `json:"tier"`
Timeformat string `json:"timeformat"`
Version string `json:"version"`
}
type Statistics struct {
OpenTicketsPerUser map[string]int `json:"open_tickets_per_user"`
TicketsPerType map[string]int `json:"tickets_per_type"`
TicketsPerWeek map[string]int `json:"tickets_per_week"`
Unassigned int `json:"unassigned"`
}
type Task struct {
Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"`
Created time.Time `json:"created"`
Data map[string]interface{} `json:"data,omitempty"`
Done bool `json:"done"`
Join *bool `json:"join,omitempty"`
Name string `json:"name"`
Next map[string]string `json:"next,omitempty"`
Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"`
Schema map[string]interface{} `json:"schema,omitempty"`
Type string `json:"type"`
}
type TaskOrigin struct {
PlaybookId string `json:"playbook_id"`
TaskId string `json:"task_id"`
TicketId int64 `json:"ticket_id"`
}
type TaskResponse struct {
Active bool `json:"active"`
Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"`
Created time.Time `json:"created"`
Data map[string]interface{} `json:"data,omitempty"`
Done bool `json:"done"`
Join *bool `json:"join,omitempty"`
Name string `json:"name"`
Next map[string]string `json:"next,omitempty"`
Order int64 `json:"order"`
Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"`
Schema map[string]interface{} `json:"schema,omitempty"`
Type string `json:"type"`
}
type TaskWithContext struct {
PlaybookId string `json:"playbook_id"`
PlaybookName string `json:"playbook_name"`
Task *TaskResponse `json:"task"`
TaskId string `json:"task_id"`
TicketId int64 `json:"ticket_id"`
TicketName string `json:"ticket_name"`
}
type Ticket struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*Playbook `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketForm struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created *time.Time `json:"created,omitempty"`
Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID *int64 `json:"id,omitempty"`
Modified *time.Time `json:"modified,omitempty"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks []*PlaybookTemplateForm `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema *string `json:"schema,omitempty"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketFormArray []*TicketForm
type TicketList struct {
Count int `json:"count"`
Tickets []*TicketSimpleResponse `json:"tickets"`
}
type TicketResponse struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID int64 `json:"id"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*PlaybookResponse `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketSimpleResponse struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID int64 `json:"id"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*Playbook `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketTemplate struct {
Name string `json:"name"`
Schema string `json:"schema"`
}
type TicketTemplateForm struct {
ID *string `json:"id,omitempty"`
Name string `json:"name"`
Schema string `json:"schema"`
}
type TicketTemplateResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Schema string `json:"schema"`
}
type TicketType struct {
DefaultGroups []string `json:"default_groups,omitempty"`
DefaultPlaybooks []string `json:"default_playbooks"`
DefaultTemplate string `json:"default_template"`
Icon string `json:"icon"`
Name string `json:"name"`
}
type TicketTypeForm struct {
DefaultGroups []string `json:"default_groups,omitempty"`
DefaultPlaybooks []string `json:"default_playbooks"`
DefaultTemplate string `json:"default_template"`
Icon string `json:"icon"`
ID *string `json:"id,omitempty"`
Name string `json:"name"`
}
type TicketTypeResponse struct {
DefaultGroups []string `json:"default_groups,omitempty"`
DefaultPlaybooks []string `json:"default_playbooks"`
DefaultTemplate string `json:"default_template"`
Icon string `json:"icon"`
ID string `json:"id"`
Name string `json:"name"`
}
type TicketWithTickets struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details map[string]interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID int64 `json:"id"`
Logs []*LogEntry `json:"logs,omitempty"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*PlaybookResponse `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Tickets []*TicketSimpleResponse `json:"tickets,omitempty"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type Type struct {
Color *string `json:"color,omitempty"`
Icon string `json:"icon"`
ID string `json:"id"`
Name string `json:"name"`
}
type User struct {
Apikey bool `json:"apikey"`
Blocked bool `json:"blocked"`
Roles []string `json:"roles"`
Sha256 *string `json:"sha256,omitempty"`
}
type UserData struct {
Email *string `json:"email,omitempty"`
Image *string `json:"image,omitempty"`
Name *string `json:"name,omitempty"`
Timeformat *string `json:"timeformat,omitempty"`
}
type UserDataResponse struct {
Email *string `json:"email,omitempty"`
ID string `json:"id"`
Image *string `json:"image,omitempty"`
Name *string `json:"name,omitempty"`
Timeformat *string `json:"timeformat,omitempty"`
}
type UserForm struct {
Apikey bool `json:"apikey"`
Blocked bool `json:"blocked"`
ID string `json:"id"`
Roles []string `json:"roles"`
}
type UserResponse struct {
Apikey bool `json:"apikey"`
Blocked bool `json:"blocked"`
ID string `json:"id"`
Roles []string `json:"roles"`
}
type Widget struct {
Aggregation string `json:"aggregation"`
Filter *string `json:"filter,omitempty"`
Name string `json:"name"`
Type string `json:"type"`
Width int `json:"width"`
}
func mustCompile(uri string) *gojsonschema.Schema {
s, err := schemaLoader.Compile(gojsonschema.NewReferenceLoader(uri))
if err != nil {
panic(err)
}
return s
}
const (
SettingsResponseTierCommunity = "community"
SettingsResponseTierEnterprise = "enterprise"
TaskTypeTask = "task"
TaskTypeInput = "input"
TaskTypeAutomation = "automation"
TaskResponseTypeTask = "task"
TaskResponseTypeInput = "input"
TaskResponseTypeAutomation = "automation"
TypeColorError = "error"
TypeColorInfo = "info"
TypeColorSuccess = "success"
TypeColorWarning = "warning"
WidgetTypeBar = "bar"
WidgetTypeLine = "line"
WidgetTypePie = "pie"
)

View File

@@ -1,643 +0,0 @@
package models
import (
"fmt"
"strings"
"time"
"github.com/xeipuuv/gojsonschema"
)
var (
schemaLoader = gojsonschema.NewSchemaLoader()
ArtifactSchema = new(gojsonschema.Schema)
ArtifactOriginSchema = new(gojsonschema.Schema)
AutomationSchema = new(gojsonschema.Schema)
AutomationFormSchema = new(gojsonschema.Schema)
AutomationResponseSchema = new(gojsonschema.Schema)
CommentSchema = new(gojsonschema.Schema)
CommentFormSchema = new(gojsonschema.Schema)
ContextSchema = new(gojsonschema.Schema)
EnrichmentSchema = new(gojsonschema.Schema)
EnrichmentFormSchema = new(gojsonschema.Schema)
FileSchema = new(gojsonschema.Schema)
JobSchema = new(gojsonschema.Schema)
JobFormSchema = new(gojsonschema.Schema)
JobResponseSchema = new(gojsonschema.Schema)
LogEntrySchema = new(gojsonschema.Schema)
MessageSchema = new(gojsonschema.Schema)
NewUserResponseSchema = new(gojsonschema.Schema)
OriginSchema = new(gojsonschema.Schema)
PlaybookSchema = new(gojsonschema.Schema)
PlaybookResponseSchema = new(gojsonschema.Schema)
PlaybookTemplateSchema = new(gojsonschema.Schema)
PlaybookTemplateFormSchema = new(gojsonschema.Schema)
PlaybookTemplateResponseSchema = new(gojsonschema.Schema)
ReferenceSchema = new(gojsonschema.Schema)
SettingsSchema = new(gojsonschema.Schema)
StatisticsSchema = new(gojsonschema.Schema)
TaskSchema = new(gojsonschema.Schema)
TaskFormSchema = new(gojsonschema.Schema)
TaskOriginSchema = new(gojsonschema.Schema)
TaskResponseSchema = new(gojsonschema.Schema)
TaskWithContextSchema = new(gojsonschema.Schema)
TicketSchema = new(gojsonschema.Schema)
TicketFormSchema = new(gojsonschema.Schema)
TicketListSchema = new(gojsonschema.Schema)
TicketResponseSchema = new(gojsonschema.Schema)
TicketSimpleResponseSchema = new(gojsonschema.Schema)
TicketTemplateSchema = new(gojsonschema.Schema)
TicketTemplateFormSchema = new(gojsonschema.Schema)
TicketTemplateResponseSchema = new(gojsonschema.Schema)
TicketTypeSchema = new(gojsonschema.Schema)
TicketTypeFormSchema = new(gojsonschema.Schema)
TicketTypeResponseSchema = new(gojsonschema.Schema)
TicketWithTicketsSchema = new(gojsonschema.Schema)
TypeSchema = new(gojsonschema.Schema)
UserSchema = new(gojsonschema.Schema)
UserDataSchema = new(gojsonschema.Schema)
UserDataResponseSchema = new(gojsonschema.Schema)
UserFormSchema = new(gojsonschema.Schema)
UserResponseSchema = new(gojsonschema.Schema)
)
func init() {
err := schemaLoader.AddSchemas(
gojsonschema.NewStringLoader(`{"type":"object","required":["name"],"x-embed":"","properties":{"enrichments":{"type":"object","additionalProperties":{"$ref":"#/definitions/Enrichment"}},"name":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"}},"$id":"#/definitions/Artifact"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["ticket_id","artifact"],"x-embed":"","properties":{"artifact":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"$id":"#/definitions/ArtifactOrigin"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["image","script","type"],"x-embed":"","properties":{"image":{"type":"string"},"schema":{"type":"string"},"script":{"type":"string"},"type":{"items":{"type":"string","enum":["artifact","playbook","global"]},"type":"array"}},"$id":"#/definitions/Automation"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","image","script","type"],"x-embed":"","properties":{"id":{"type":"string"},"image":{"type":"string"},"schema":{"type":"string"},"script":{"type":"string"},"type":{"items":{"type":"string","enum":["artifact","playbook","global"]},"type":"array"}},"$id":"#/definitions/AutomationForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","image","script","type"],"x-embed":"","properties":{"id":{"type":"string"},"image":{"type":"string"},"schema":{"type":"string"},"script":{"type":"string"},"type":{"items":{"type":"string","enum":["artifact","playbook","global"]},"type":"array"}},"$id":"#/definitions/AutomationResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["creator","created","message"],"x-embed":"","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"}},"$id":"#/definitions/Comment"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["message"],"x-embed":"","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"}},"$id":"#/definitions/CommentForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"artifact":{"$ref":"#/definitions/Artifact"},"playbook":{"$ref":"#/definitions/PlaybookResponse"},"task":{"$ref":"#/definitions/TaskResponse"},"ticket":{"$ref":"#/definitions/TicketResponse"}},"$id":"#/definitions/Context"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","data","created"],"x-embed":"","properties":{"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"name":{"type":"string"}},"$id":"#/definitions/Enrichment"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","data"],"x-embed":"","properties":{"data":{"type":"object"},"name":{"type":"string"}},"$id":"#/definitions/EnrichmentForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["key","name"],"x-embed":"","properties":{"key":{"type":"string"},"name":{"type":"string"}},"$id":"#/definitions/File"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["automation","running","status"],"x-embed":"","properties":{"automation":{"type":"string"},"container":{"type":"string"},"log":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"output":{"type":"object"},"payload":{},"running":{"type":"boolean"},"status":{"type":"string"}},"$id":"#/definitions/Job"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["automation"],"x-embed":"","properties":{"automation":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"payload":{}},"$id":"#/definitions/JobForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","automation","status"],"x-embed":"","properties":{"automation":{"type":"string"},"container":{"type":"string"},"id":{"type":"string"},"log":{"type":"string"},"origin":{"$ref":"#/definitions/Origin"},"output":{"type":"object"},"payload":{},"status":{"type":"string"}},"$id":"#/definitions/JobResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["reference","creator","created","message"],"x-embed":"","properties":{"created":{"format":"date-time","type":"string"},"creator":{"type":"string"},"message":{"type":"string"},"reference":{"type":"string"}},"$id":"#/definitions/LogEntry"}`),
gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"context":{"$ref":"#/definitions/Context"},"payload":{"type":"object"},"secrets":{"type":"object","additionalProperties":{"type":"string"}}},"$id":"#/definitions/Message"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","blocked","roles"],"x-embed":"","properties":{"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"},"secret":{"type":"string"}},"$id":"#/definitions/NewUserResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"artifact_origin":{"$ref":"#/definitions/ArtifactOrigin"},"task_origin":{"$ref":"#/definitions/TaskOrigin"}},"$id":"#/definitions/Origin"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","tasks"],"x-embed":"","properties":{"name":{"type":"string"},"tasks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Task"}}},"$id":"#/definitions/Playbook"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","tasks"],"x-embed":"","properties":{"name":{"type":"string"},"tasks":{"type":"object","additionalProperties":{"$ref":"#/definitions/TaskResponse"}}},"$id":"#/definitions/PlaybookResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","yaml"],"x-embed":"","properties":{"name":{"type":"string"},"yaml":{"type":"string"}},"$id":"#/definitions/PlaybookTemplate"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["yaml"],"x-embed":"","properties":{"id":{"type":"string"},"yaml":{"type":"string"}},"$id":"#/definitions/PlaybookTemplateForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","yaml"],"x-embed":"","properties":{"id":{"type":"string"},"name":{"type":"string"},"yaml":{"type":"string"}},"$id":"#/definitions/PlaybookTemplateResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","href"],"x-embed":"","properties":{"href":{"type":"string"},"name":{"type":"string"}},"$id":"#/definitions/Reference"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["version","tier","timeformat","ticketTypes","artifactStates"],"x-embed":"","properties":{"artifactStates":{"title":"Artifact States","items":{"$ref":"#/definitions/Type"},"type":"array"},"roles":{"title":"Roles","items":{"type":"string"},"type":"array"},"ticketTypes":{"title":"Ticket Types","items":{"$ref":"#/definitions/TicketTypeResponse"},"type":"array"},"tier":{"title":"Tier","type":"string","enum":["community","enterprise"]},"timeformat":{"title":"Time Format","type":"string"},"version":{"title":"Version","type":"string"}},"$id":"#/definitions/Settings"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["unassigned","open_tickets_per_user","tickets_per_week","tickets_per_type"],"x-embed":"","properties":{"open_tickets_per_user":{"type":"object","additionalProperties":{"type":"integer"}},"tickets_per_type":{"type":"object","additionalProperties":{"type":"integer"}},"tickets_per_week":{"type":"object","additionalProperties":{"type":"integer"}},"unassigned":{"type":"integer"}},"$id":"#/definitions/Statistics"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","type","done","created"],"x-embed":"","properties":{"automation":{"type":"string"},"closed":{"format":"date-time","type":"string"},"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"done":{"type":"boolean"},"join":{"type":"boolean"},"name":{"type":"string"},"next":{"type":"object","additionalProperties":{"type":"string"}},"owner":{"type":"string"},"payload":{"type":"object","additionalProperties":{"type":"string"}},"schema":{"type":"object"},"type":{"type":"string","enum":["task","input","automation"]}},"$id":"#/definitions/Task"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","type"],"x-embed":"","properties":{"automation":{"type":"string"},"closed":{"format":"date-time","type":"string"},"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"done":{"type":"boolean"},"join":{"type":"boolean"},"name":{"type":"string"},"next":{"type":"object","additionalProperties":{"type":"string"}},"owner":{"type":"string"},"payload":{"type":"object","additionalProperties":{"type":"string"}},"schema":{"type":"object"},"type":{"type":"string","enum":["task","input","automation"]}},"$id":"#/definitions/TaskForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["ticket_id","playbook_id","task_id"],"x-embed":"","properties":{"playbook_id":{"type":"string"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"integer"}},"$id":"#/definitions/TaskOrigin"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","type","done","created","order","active"],"x-embed":"","properties":{"active":{"type":"boolean"},"automation":{"type":"string"},"closed":{"format":"date-time","type":"string"},"created":{"format":"date-time","type":"string"},"data":{"type":"object"},"done":{"type":"boolean"},"join":{"type":"boolean"},"name":{"type":"string"},"next":{"type":"object","additionalProperties":{"type":"string"}},"order":{"format":"int64","type":"number"},"owner":{"type":"string"},"payload":{"type":"object","additionalProperties":{"type":"string"}},"schema":{"type":"object"},"type":{"type":"string","enum":["task","input","automation"]}},"$id":"#/definitions/TaskResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["ticket_id","ticket_name","playbook_id","playbook_name","task_id","task"],"x-embed":"","properties":{"playbook_id":{"type":"string"},"playbook_name":{"type":"string"},"task":{"$ref":"#/definitions/TaskResponse"},"task_id":{"type":"string"},"ticket_id":{"format":"int64","type":"number"},"ticket_name":{"type":"string"}},"$id":"#/definitions/TaskWithContext"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","type","status","created","modified","schema"],"x-embed":"","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Playbook"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/Ticket"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","type","status"],"x-embed":"","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"items":{"$ref":"#/definitions/PlaybookTemplateForm"},"type":"array"},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/TicketForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["tickets","count"],"x-embed":"","properties":{"count":{"type":"number"},"tickets":{"items":{"$ref":"#/definitions/TicketSimpleResponse"},"type":"array"}},"$id":"#/definitions/TicketList"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","type","status","created","modified","schema"],"x-embed":"","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/PlaybookResponse"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/TicketResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","type","status","created","modified","schema"],"x-embed":"","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/Playbook"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/TicketSimpleResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","schema"],"x-embed":"","properties":{"name":{"type":"string"},"schema":{"type":"string"}},"$id":"#/definitions/TicketTemplate"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","schema"],"x-embed":"","properties":{"id":{"type":"string"},"name":{"type":"string"},"schema":{"type":"string"}},"$id":"#/definitions/TicketTemplateForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","schema"],"x-embed":"","properties":{"id":{"type":"string"},"name":{"type":"string"},"schema":{"type":"string"}},"$id":"#/definitions/TicketTemplateResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","icon","default_template","default_playbooks"],"x-embed":"","properties":{"default_groups":{"items":{"type":"string"},"type":"array"},"default_playbooks":{"items":{"type":"string"},"type":"array"},"default_template":{"type":"string"},"icon":{"type":"string"},"name":{"type":"string"}},"$id":"#/definitions/TicketType"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["name","icon","default_template","default_playbooks"],"x-embed":"","properties":{"default_groups":{"items":{"type":"string"},"type":"array"},"default_playbooks":{"items":{"type":"string"},"type":"array"},"default_template":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"}},"$id":"#/definitions/TicketTypeForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","icon","default_template","default_playbooks"],"x-embed":"","properties":{"default_groups":{"items":{"type":"string"},"type":"array"},"default_playbooks":{"items":{"type":"string"},"type":"array"},"default_template":{"type":"string"},"icon":{"type":"string"},"id":{"type":"string"},"name":{"type":"string"}},"$id":"#/definitions/TicketTypeResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","type","status","created","modified","schema"],"x-embed":"","properties":{"artifacts":{"items":{"$ref":"#/definitions/Artifact"},"type":"array"},"comments":{"items":{"$ref":"#/definitions/Comment"},"type":"array"},"created":{"format":"date-time","type":"string"},"details":{"type":"object"},"files":{"items":{"$ref":"#/definitions/File"},"type":"array"},"id":{"format":"int64","type":"integer"},"modified":{"format":"date-time","type":"string"},"name":{"type":"string"},"owner":{"type":"string"},"playbooks":{"type":"object","additionalProperties":{"$ref":"#/definitions/PlaybookResponse"}},"read":{"items":{"type":"string"},"type":"array"},"references":{"items":{"$ref":"#/definitions/Reference"},"type":"array"},"schema":{"type":"string"},"status":{"type":"string"},"tickets":{"items":{"$ref":"#/definitions/TicketSimpleResponse"},"type":"array"},"type":{"type":"string"},"write":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/TicketWithTickets"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","name","icon"],"x-embed":"","properties":{"color":{"title":"Color","type":"string","enum":["error","info","success","warning"]},"icon":{"title":"Icon (https://materialdesignicons.com)","type":"string"},"id":{"title":"ID","type":"string"},"name":{"title":"Name","type":"string"}},"$id":"#/definitions/Type"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["blocked","apikey","roles"],"x-embed":"","properties":{"apikey":{"type":"boolean"},"blocked":{"type":"boolean"},"roles":{"items":{"type":"string"},"type":"array"},"sha256":{"type":"string"}},"$id":"#/definitions/User"}`),
gojsonschema.NewStringLoader(`{"type":"object","x-embed":"","properties":{"email":{"type":"string"},"image":{"type":"string"},"name":{"type":"string"},"timeformat":{"title":"Time Format (https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens)","type":"string"}},"$id":"#/definitions/UserData"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id"],"x-embed":"","properties":{"email":{"type":"string"},"id":{"type":"string"},"image":{"type":"string"},"name":{"type":"string"},"timeformat":{"title":"Time Format (https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens)","type":"string"}},"$id":"#/definitions/UserDataResponse"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","blocked","roles","apikey"],"x-embed":"","properties":{"apikey":{"type":"boolean"},"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/UserForm"}`),
gojsonschema.NewStringLoader(`{"type":"object","required":["id","blocked","roles","apikey"],"x-embed":"","properties":{"apikey":{"type":"boolean"},"blocked":{"type":"boolean"},"id":{"type":"string"},"roles":{"items":{"type":"string"},"type":"array"}},"$id":"#/definitions/UserResponse"}`),
)
if err != nil {
panic(err)
}
ArtifactSchema = mustCompile(`#/definitions/Artifact`)
ArtifactOriginSchema = mustCompile(`#/definitions/ArtifactOrigin`)
AutomationSchema = mustCompile(`#/definitions/Automation`)
AutomationFormSchema = mustCompile(`#/definitions/AutomationForm`)
AutomationResponseSchema = mustCompile(`#/definitions/AutomationResponse`)
CommentSchema = mustCompile(`#/definitions/Comment`)
CommentFormSchema = mustCompile(`#/definitions/CommentForm`)
ContextSchema = mustCompile(`#/definitions/Context`)
EnrichmentSchema = mustCompile(`#/definitions/Enrichment`)
EnrichmentFormSchema = mustCompile(`#/definitions/EnrichmentForm`)
FileSchema = mustCompile(`#/definitions/File`)
JobSchema = mustCompile(`#/definitions/Job`)
JobFormSchema = mustCompile(`#/definitions/JobForm`)
JobResponseSchema = mustCompile(`#/definitions/JobResponse`)
LogEntrySchema = mustCompile(`#/definitions/LogEntry`)
MessageSchema = mustCompile(`#/definitions/Message`)
NewUserResponseSchema = mustCompile(`#/definitions/NewUserResponse`)
OriginSchema = mustCompile(`#/definitions/Origin`)
PlaybookSchema = mustCompile(`#/definitions/Playbook`)
PlaybookResponseSchema = mustCompile(`#/definitions/PlaybookResponse`)
PlaybookTemplateSchema = mustCompile(`#/definitions/PlaybookTemplate`)
PlaybookTemplateFormSchema = mustCompile(`#/definitions/PlaybookTemplateForm`)
PlaybookTemplateResponseSchema = mustCompile(`#/definitions/PlaybookTemplateResponse`)
ReferenceSchema = mustCompile(`#/definitions/Reference`)
SettingsSchema = mustCompile(`#/definitions/Settings`)
StatisticsSchema = mustCompile(`#/definitions/Statistics`)
TaskSchema = mustCompile(`#/definitions/Task`)
TaskFormSchema = mustCompile(`#/definitions/TaskForm`)
TaskOriginSchema = mustCompile(`#/definitions/TaskOrigin`)
TaskResponseSchema = mustCompile(`#/definitions/TaskResponse`)
TaskWithContextSchema = mustCompile(`#/definitions/TaskWithContext`)
TicketSchema = mustCompile(`#/definitions/Ticket`)
TicketFormSchema = mustCompile(`#/definitions/TicketForm`)
TicketListSchema = mustCompile(`#/definitions/TicketList`)
TicketResponseSchema = mustCompile(`#/definitions/TicketResponse`)
TicketSimpleResponseSchema = mustCompile(`#/definitions/TicketSimpleResponse`)
TicketTemplateSchema = mustCompile(`#/definitions/TicketTemplate`)
TicketTemplateFormSchema = mustCompile(`#/definitions/TicketTemplateForm`)
TicketTemplateResponseSchema = mustCompile(`#/definitions/TicketTemplateResponse`)
TicketTypeSchema = mustCompile(`#/definitions/TicketType`)
TicketTypeFormSchema = mustCompile(`#/definitions/TicketTypeForm`)
TicketTypeResponseSchema = mustCompile(`#/definitions/TicketTypeResponse`)
TicketWithTicketsSchema = mustCompile(`#/definitions/TicketWithTickets`)
TypeSchema = mustCompile(`#/definitions/Type`)
UserSchema = mustCompile(`#/definitions/User`)
UserDataSchema = mustCompile(`#/definitions/UserData`)
UserDataResponseSchema = mustCompile(`#/definitions/UserDataResponse`)
UserFormSchema = mustCompile(`#/definitions/UserForm`)
UserResponseSchema = mustCompile(`#/definitions/UserResponse`)
}
type Artifact struct {
Enrichments map[string]*Enrichment `json:"enrichments,omitempty"`
Name string `json:"name"`
Status *string `json:"status,omitempty"`
Type *string `json:"type,omitempty"`
}
type ArtifactOrigin struct {
Artifact string `json:"artifact"`
TicketId int64 `json:"ticket_id"`
}
type Automation struct {
Image string `json:"image"`
Schema *string `json:"schema,omitempty"`
Script string `json:"script"`
Type []string `json:"type"`
}
type AutomationForm struct {
ID string `json:"id"`
Image string `json:"image"`
Schema *string `json:"schema,omitempty"`
Script string `json:"script"`
Type []string `json:"type"`
}
type AutomationResponse struct {
ID string `json:"id"`
Image string `json:"image"`
Schema *string `json:"schema,omitempty"`
Script string `json:"script"`
Type []string `json:"type"`
}
type Comment struct {
Created time.Time `json:"created"`
Creator string `json:"creator"`
Message string `json:"message"`
}
type CommentForm struct {
Created *time.Time `json:"created,omitempty"`
Creator *string `json:"creator,omitempty"`
Message string `json:"message"`
}
type Context struct {
Artifact *Artifact `json:"artifact,omitempty"`
Playbook *PlaybookResponse `json:"playbook,omitempty"`
Task *TaskResponse `json:"task,omitempty"`
Ticket *TicketResponse `json:"ticket,omitempty"`
}
type Enrichment struct {
Created time.Time `json:"created"`
Data interface{} `json:"data"`
Name string `json:"name"`
}
type EnrichmentForm struct {
Data interface{} `json:"data"`
Name string `json:"name"`
}
type File struct {
Key string `json:"key"`
Name string `json:"name"`
}
type Job struct {
Automation string `json:"automation"`
Container *string `json:"container,omitempty"`
Log *string `json:"log,omitempty"`
Origin *Origin `json:"origin,omitempty"`
Output interface{} `json:"output,omitempty"`
Payload interface{} `json:"payload,omitempty"`
Running bool `json:"running"`
Status string `json:"status"`
}
type JobForm struct {
Automation string `json:"automation"`
Origin *Origin `json:"origin,omitempty"`
Payload interface{} `json:"payload,omitempty"`
}
type JobResponse struct {
Automation string `json:"automation"`
Container *string `json:"container,omitempty"`
ID string `json:"id"`
Log *string `json:"log,omitempty"`
Origin *Origin `json:"origin,omitempty"`
Output interface{} `json:"output,omitempty"`
Payload interface{} `json:"payload,omitempty"`
Status string `json:"status"`
}
type LogEntry struct {
Created time.Time `json:"created"`
Creator string `json:"creator"`
Message string `json:"message"`
Reference string `json:"reference"`
}
type Message struct {
Context *Context `json:"context,omitempty"`
Payload interface{} `json:"payload,omitempty"`
Secrets map[string]string `json:"secrets,omitempty"`
}
type NewUserResponse struct {
Blocked bool `json:"blocked"`
ID string `json:"id"`
Roles []string `json:"roles"`
Secret *string `json:"secret,omitempty"`
}
type Origin struct {
ArtifactOrigin *ArtifactOrigin `json:"artifact_origin,omitempty"`
TaskOrigin *TaskOrigin `json:"task_origin,omitempty"`
}
type Playbook struct {
Name string `json:"name"`
Tasks map[string]*Task `json:"tasks"`
}
type PlaybookResponse struct {
Name string `json:"name"`
Tasks map[string]*TaskResponse `json:"tasks"`
}
type PlaybookTemplate struct {
Name string `json:"name"`
Yaml string `json:"yaml"`
}
type PlaybookTemplateForm struct {
ID *string `json:"id,omitempty"`
Yaml string `json:"yaml"`
}
type PlaybookTemplateResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Yaml string `json:"yaml"`
}
type Reference struct {
Href string `json:"href"`
Name string `json:"name"`
}
type Settings struct {
ArtifactStates []*Type `json:"artifactStates"`
Roles []string `json:"roles,omitempty"`
TicketTypes []*TicketTypeResponse `json:"ticketTypes"`
Tier string `json:"tier"`
Timeformat string `json:"timeformat"`
Version string `json:"version"`
}
type Statistics struct {
OpenTicketsPerUser map[string]int `json:"open_tickets_per_user"`
TicketsPerType map[string]int `json:"tickets_per_type"`
TicketsPerWeek map[string]int `json:"tickets_per_week"`
Unassigned int `json:"unassigned"`
}
type Task struct {
Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"`
Created time.Time `json:"created"`
Data interface{} `json:"data,omitempty"`
Done bool `json:"done"`
Join *bool `json:"join,omitempty"`
Name string `json:"name"`
Next map[string]string `json:"next,omitempty"`
Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"`
Schema interface{} `json:"schema,omitempty"`
Type string `json:"type"`
}
type TaskForm struct {
Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"`
Created *time.Time `json:"created,omitempty"`
Data interface{} `json:"data,omitempty"`
Done *bool `json:"done,omitempty"`
Join *bool `json:"join,omitempty"`
Name string `json:"name"`
Next map[string]string `json:"next,omitempty"`
Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"`
Schema interface{} `json:"schema,omitempty"`
Type string `json:"type"`
}
type TaskOrigin struct {
PlaybookId string `json:"playbook_id"`
TaskId string `json:"task_id"`
TicketId int64 `json:"ticket_id"`
}
type TaskResponse struct {
Active bool `json:"active"`
Automation *string `json:"automation,omitempty"`
Closed *time.Time `json:"closed,omitempty"`
Created time.Time `json:"created"`
Data interface{} `json:"data,omitempty"`
Done bool `json:"done"`
Join *bool `json:"join,omitempty"`
Name string `json:"name"`
Next map[string]string `json:"next,omitempty"`
Order int64 `json:"order"`
Owner *string `json:"owner,omitempty"`
Payload map[string]string `json:"payload,omitempty"`
Schema interface{} `json:"schema,omitempty"`
Type string `json:"type"`
}
type TaskWithContext struct {
PlaybookId string `json:"playbook_id"`
PlaybookName string `json:"playbook_name"`
Task TaskResponse `json:"task"`
TaskId string `json:"task_id"`
TicketId int64 `json:"ticket_id"`
TicketName string `json:"ticket_name"`
}
type Ticket struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*Playbook `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketForm struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created *time.Time `json:"created,omitempty"`
Details interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID *int64 `json:"id,omitempty"`
Modified *time.Time `json:"modified,omitempty"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks []*PlaybookTemplateForm `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema *string `json:"schema,omitempty"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketList struct {
Count int `json:"count"`
Tickets []*TicketSimpleResponse `json:"tickets"`
}
type TicketResponse struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID int64 `json:"id"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*PlaybookResponse `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketSimpleResponse struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID int64 `json:"id"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*Playbook `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type TicketTemplate struct {
Name string `json:"name"`
Schema string `json:"schema"`
}
type TicketTemplateForm struct {
ID *string `json:"id,omitempty"`
Name string `json:"name"`
Schema string `json:"schema"`
}
type TicketTemplateResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Schema string `json:"schema"`
}
type TicketType struct {
DefaultGroups []string `json:"default_groups,omitempty"`
DefaultPlaybooks []string `json:"default_playbooks"`
DefaultTemplate string `json:"default_template"`
Icon string `json:"icon"`
Name string `json:"name"`
}
type TicketTypeForm struct {
DefaultGroups []string `json:"default_groups,omitempty"`
DefaultPlaybooks []string `json:"default_playbooks"`
DefaultTemplate string `json:"default_template"`
Icon string `json:"icon"`
ID *string `json:"id,omitempty"`
Name string `json:"name"`
}
type TicketTypeResponse struct {
DefaultGroups []string `json:"default_groups,omitempty"`
DefaultPlaybooks []string `json:"default_playbooks"`
DefaultTemplate string `json:"default_template"`
Icon string `json:"icon"`
ID string `json:"id"`
Name string `json:"name"`
}
type TicketWithTickets struct {
Artifacts []*Artifact `json:"artifacts,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Created time.Time `json:"created"`
Details interface{} `json:"details,omitempty"`
Files []*File `json:"files,omitempty"`
ID int64 `json:"id"`
Modified time.Time `json:"modified"`
Name string `json:"name"`
Owner *string `json:"owner,omitempty"`
Playbooks map[string]*PlaybookResponse `json:"playbooks,omitempty"`
Read []string `json:"read,omitempty"`
References []*Reference `json:"references,omitempty"`
Schema string `json:"schema"`
Status string `json:"status"`
Tickets []*TicketSimpleResponse `json:"tickets,omitempty"`
Type string `json:"type"`
Write []string `json:"write,omitempty"`
}
type Type struct {
Color *string `json:"color,omitempty"`
Icon string `json:"icon"`
ID string `json:"id"`
Name string `json:"name"`
}
type User struct {
Apikey bool `json:"apikey"`
Blocked bool `json:"blocked"`
Roles []string `json:"roles"`
Sha256 *string `json:"sha256,omitempty"`
}
type UserData struct {
Email *string `json:"email,omitempty"`
Image *string `json:"image,omitempty"`
Name *string `json:"name,omitempty"`
Timeformat *string `json:"timeformat,omitempty"`
}
type UserDataResponse struct {
Email *string `json:"email,omitempty"`
ID string `json:"id"`
Image *string `json:"image,omitempty"`
Name *string `json:"name,omitempty"`
Timeformat *string `json:"timeformat,omitempty"`
}
type UserForm struct {
Apikey bool `json:"apikey"`
Blocked bool `json:"blocked"`
ID string `json:"id"`
Roles []string `json:"roles"`
}
type UserResponse struct {
Apikey bool `json:"apikey"`
Blocked bool `json:"blocked"`
ID string `json:"id"`
Roles []string `json:"roles"`
}
func mustCompile(uri string) *gojsonschema.Schema {
s, err := schemaLoader.Compile(gojsonschema.NewReferenceLoader(uri))
if err != nil {
panic(err)
}
return s
}
func validate(s *gojsonschema.Schema, b []byte) error {
res, err := s.Validate(gojsonschema.NewStringLoader(string(b)))
if err != nil {
return err
}
if len(res.Errors()) > 0 {
var l []string
for _, e := range res.Errors() {
l = append(l, e.String())
}
return fmt.Errorf("validation failed: %v", strings.Join(l, ", "))
}
return nil
}
const (
SettingsTierCommunity = "community"
SettingsTierEnterprise = "enterprise"
TaskTypeTask = "task"
TaskTypeInput = "input"
TaskTypeAutomation = "automation"
TaskFormTypeTask = "task"
TaskFormTypeInput = "input"
TaskFormTypeAutomation = "automation"
TaskResponseTypeTask = "task"
TaskResponseTypeInput = "input"
TaskResponseTypeAutomation = "automation"
TypeColorError = "error"
TypeColorInfo = "info"
TypeColorSuccess = "success"
TypeColorWarning = "warning"
)

0
pointer/pointer.go → generated/pointer/pointer.go Normal file → Executable file
View File

View File

@@ -1,252 +0,0 @@
package restapi
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/automations"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/jobs"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/logs"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/playbooks"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/settings"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/statistics"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/tasks"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/templates"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/tickets"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/tickettypes"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/userdata"
"github.com/SecurityBrewery/catalyst/generated/restapi/operations/users"
"github.com/SecurityBrewery/catalyst/role"
)
// Service is the interface that must be implemented in order to provide
// business logic for the Server service.
type Service interface {
AddArtifact(ctx context.Context, params *tickets.AddArtifactParams) *api.Response
AddComment(ctx context.Context, params *tickets.AddCommentParams) *api.Response
AddTicketPlaybook(ctx context.Context, params *tickets.AddTicketPlaybookParams) *api.Response
CompleteTask(ctx context.Context, params *tickets.CompleteTaskParams) *api.Response
CreateAutomation(ctx context.Context, params *automations.CreateAutomationParams) *api.Response
CreatePlaybook(ctx context.Context, params *playbooks.CreatePlaybookParams) *api.Response
CreateTemplate(ctx context.Context, params *templates.CreateTemplateParams) *api.Response
CreateTicket(ctx context.Context, params *tickets.CreateTicketParams) *api.Response
CreateTicketBatch(ctx context.Context, params *tickets.CreateTicketBatchParams) *api.Response
CreateTicketType(ctx context.Context, params *tickettypes.CreateTicketTypeParams) *api.Response
CreateUser(ctx context.Context, params *users.CreateUserParams) *api.Response
CurrentUser(ctx context.Context) *api.Response
CurrentUserData(ctx context.Context) *api.Response
DeleteAutomation(ctx context.Context, params *automations.DeleteAutomationParams) *api.Response
DeletePlaybook(ctx context.Context, params *playbooks.DeletePlaybookParams) *api.Response
DeleteTemplate(ctx context.Context, params *templates.DeleteTemplateParams) *api.Response
DeleteTicket(ctx context.Context, params *tickets.DeleteTicketParams) *api.Response
DeleteTicketType(ctx context.Context, params *tickettypes.DeleteTicketTypeParams) *api.Response
DeleteUser(ctx context.Context, params *users.DeleteUserParams) *api.Response
EnrichArtifact(ctx context.Context, params *tickets.EnrichArtifactParams) *api.Response
GetArtifact(ctx context.Context, params *tickets.GetArtifactParams) *api.Response
GetAutomation(ctx context.Context, params *automations.GetAutomationParams) *api.Response
GetJob(ctx context.Context, params *jobs.GetJobParams) *api.Response
GetLogs(ctx context.Context, params *logs.GetLogsParams) *api.Response
GetPlaybook(ctx context.Context, params *playbooks.GetPlaybookParams) *api.Response
GetSettings(ctx context.Context) *api.Response
GetStatistics(ctx context.Context) *api.Response
GetTemplate(ctx context.Context, params *templates.GetTemplateParams) *api.Response
GetTicket(ctx context.Context, params *tickets.GetTicketParams) *api.Response
GetTicketType(ctx context.Context, params *tickettypes.GetTicketTypeParams) *api.Response
GetUser(ctx context.Context, params *users.GetUserParams) *api.Response
GetUserData(ctx context.Context, params *userdata.GetUserDataParams) *api.Response
LinkFiles(ctx context.Context, params *tickets.LinkFilesParams) *api.Response
LinkTicket(ctx context.Context, params *tickets.LinkTicketParams) *api.Response
ListAutomations(ctx context.Context) *api.Response
ListJobs(ctx context.Context) *api.Response
ListPlaybooks(ctx context.Context) *api.Response
ListTasks(ctx context.Context) *api.Response
ListTemplates(ctx context.Context) *api.Response
ListTicketTypes(ctx context.Context) *api.Response
ListTickets(ctx context.Context, params *tickets.ListTicketsParams) *api.Response
ListUserData(ctx context.Context) *api.Response
ListUsers(ctx context.Context) *api.Response
RemoveArtifact(ctx context.Context, params *tickets.RemoveArtifactParams) *api.Response
RemoveComment(ctx context.Context, params *tickets.RemoveCommentParams) *api.Response
RemoveTicketPlaybook(ctx context.Context, params *tickets.RemoveTicketPlaybookParams) *api.Response
RunArtifact(ctx context.Context, params *tickets.RunArtifactParams) *api.Response
RunJob(ctx context.Context, params *jobs.RunJobParams) *api.Response
RunTask(ctx context.Context, params *tickets.RunTaskParams) *api.Response
SetArtifact(ctx context.Context, params *tickets.SetArtifactParams) *api.Response
SetReferences(ctx context.Context, params *tickets.SetReferencesParams) *api.Response
SetSchema(ctx context.Context, params *tickets.SetSchemaParams) *api.Response
SetTask(ctx context.Context, params *tickets.SetTaskParams) *api.Response
UnlinkTicket(ctx context.Context, params *tickets.UnlinkTicketParams) *api.Response
UpdateAutomation(ctx context.Context, params *automations.UpdateAutomationParams) *api.Response
UpdateCurrentUserData(ctx context.Context, params *userdata.UpdateCurrentUserDataParams) *api.Response
UpdateJob(ctx context.Context, params *jobs.UpdateJobParams) *api.Response
UpdatePlaybook(ctx context.Context, params *playbooks.UpdatePlaybookParams) *api.Response
UpdateTemplate(ctx context.Context, params *templates.UpdateTemplateParams) *api.Response
UpdateTicket(ctx context.Context, params *tickets.UpdateTicketParams) *api.Response
UpdateTicketType(ctx context.Context, params *tickettypes.UpdateTicketTypeParams) *api.Response
UpdateUser(ctx context.Context, params *users.UpdateUserParams) *api.Response
UpdateUserData(ctx context.Context, params *userdata.UpdateUserDataParams) *api.Response
}
// Config defines the config options for the API server.
type Config struct {
Address string
InsecureHTTP bool
TLSCertFile string
TLSKeyFile string
}
// Server defines the Server service.
type Server struct {
*gin.Engine
config *Config
server *http.Server
service Service
ApiGroup *gin.RouterGroup
RoleAuth func([]role.Role) gin.HandlerFunc
}
// New initializes a new Server service.
func New(svc Service, config *Config) *Server {
engine := gin.New()
engine.Use(gin.Recovery())
return &Server{
Engine: engine,
service: svc,
config: config,
server: &http.Server{
Addr: config.Address,
Handler: engine,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
},
ApiGroup: engine.Group("/api"),
RoleAuth: func(i []role.Role) gin.HandlerFunc { return func(c *gin.Context) { c.Next() } },
}
}
// ConfigureRoutes configures the routes for the Server service.
// Configuring of routes includes setting up Auth if it is enabled.
func (s *Server) ConfigureRoutes() {
s.ApiGroup.POST("/tickets/:id/artifacts", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.AddArtifactEndpoint(s.service.AddArtifact))
s.ApiGroup.POST("/tickets/:id/comments", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.AddCommentEndpoint(s.service.AddComment))
s.ApiGroup.POST("/tickets/:id/playbooks", s.RoleAuth([]role.Role{}), tickets.AddTicketPlaybookEndpoint(s.service.AddTicketPlaybook))
s.ApiGroup.PUT("/tickets/:id/playbooks/:playbookID/task/:taskID/complete", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.CompleteTaskEndpoint(s.service.CompleteTask))
s.ApiGroup.POST("/automations", s.RoleAuth([]role.Role{role.AutomationWrite}), automations.CreateAutomationEndpoint(s.service.CreateAutomation))
s.ApiGroup.POST("/playbooks", s.RoleAuth([]role.Role{role.PlaybookWrite}), playbooks.CreatePlaybookEndpoint(s.service.CreatePlaybook))
s.ApiGroup.POST("/templates", s.RoleAuth([]role.Role{role.TemplateWrite}), templates.CreateTemplateEndpoint(s.service.CreateTemplate))
s.ApiGroup.POST("/tickets", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.CreateTicketEndpoint(s.service.CreateTicket))
s.ApiGroup.POST("/tickets/batch", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.CreateTicketBatchEndpoint(s.service.CreateTicketBatch))
s.ApiGroup.POST("/tickettypes", s.RoleAuth([]role.Role{role.TickettypeWrite}), tickettypes.CreateTicketTypeEndpoint(s.service.CreateTicketType))
s.ApiGroup.POST("/users", s.RoleAuth([]role.Role{role.UserWrite}), users.CreateUserEndpoint(s.service.CreateUser))
s.ApiGroup.GET("/currentuser", s.RoleAuth([]role.Role{role.CurrentuserRead}), users.CurrentUserEndpoint(s.service.CurrentUser))
s.ApiGroup.GET("/currentuserdata", s.RoleAuth([]role.Role{role.CurrentuserdataRead}), userdata.CurrentUserDataEndpoint(s.service.CurrentUserData))
s.ApiGroup.DELETE("/automations/:id", s.RoleAuth([]role.Role{role.AutomationWrite}), automations.DeleteAutomationEndpoint(s.service.DeleteAutomation))
s.ApiGroup.DELETE("/playbooks/:id", s.RoleAuth([]role.Role{role.PlaybookWrite}), playbooks.DeletePlaybookEndpoint(s.service.DeletePlaybook))
s.ApiGroup.DELETE("/templates/:id", s.RoleAuth([]role.Role{role.TemplateWrite}), templates.DeleteTemplateEndpoint(s.service.DeleteTemplate))
s.ApiGroup.DELETE("/tickets/:id", s.RoleAuth([]role.Role{role.TicketDelete}), tickets.DeleteTicketEndpoint(s.service.DeleteTicket))
s.ApiGroup.DELETE("/tickettypes/:id", s.RoleAuth([]role.Role{role.TickettypeWrite}), tickettypes.DeleteTicketTypeEndpoint(s.service.DeleteTicketType))
s.ApiGroup.DELETE("/users/:id", s.RoleAuth([]role.Role{role.UserWrite}), users.DeleteUserEndpoint(s.service.DeleteUser))
s.ApiGroup.POST("/tickets/:id/artifacts/:name/enrich", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.EnrichArtifactEndpoint(s.service.EnrichArtifact))
s.ApiGroup.GET("/tickets/:id/artifacts/:name", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.GetArtifactEndpoint(s.service.GetArtifact))
s.ApiGroup.GET("/automations/:id", s.RoleAuth([]role.Role{role.AutomationRead}), automations.GetAutomationEndpoint(s.service.GetAutomation))
s.ApiGroup.GET("/jobs/:id", s.RoleAuth([]role.Role{role.JobRead}), jobs.GetJobEndpoint(s.service.GetJob))
s.ApiGroup.GET("/logs/:reference", s.RoleAuth([]role.Role{role.LogRead}), logs.GetLogsEndpoint(s.service.GetLogs))
s.ApiGroup.GET("/playbooks/:id", s.RoleAuth([]role.Role{role.PlaybookRead}), playbooks.GetPlaybookEndpoint(s.service.GetPlaybook))
s.ApiGroup.GET("/settings", s.RoleAuth([]role.Role{role.SettingsRead}), settings.GetSettingsEndpoint(s.service.GetSettings))
s.ApiGroup.GET("/statistics", s.RoleAuth([]role.Role{role.TicketRead}), statistics.GetStatisticsEndpoint(s.service.GetStatistics))
s.ApiGroup.GET("/templates/:id", s.RoleAuth([]role.Role{role.TemplateRead}), templates.GetTemplateEndpoint(s.service.GetTemplate))
s.ApiGroup.GET("/tickets/:id", s.RoleAuth([]role.Role{role.TicketRead}), tickets.GetTicketEndpoint(s.service.GetTicket))
s.ApiGroup.GET("/tickettypes/:id", s.RoleAuth([]role.Role{role.TickettypeRead}), tickettypes.GetTicketTypeEndpoint(s.service.GetTicketType))
s.ApiGroup.GET("/users/:id", s.RoleAuth([]role.Role{role.UserRead}), users.GetUserEndpoint(s.service.GetUser))
s.ApiGroup.GET("/userdata/:id", s.RoleAuth([]role.Role{role.UserdataRead}), userdata.GetUserDataEndpoint(s.service.GetUserData))
s.ApiGroup.PUT("/tickets/:id/files", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.LinkFilesEndpoint(s.service.LinkFiles))
s.ApiGroup.PATCH("/tickets/:id/tickets", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.LinkTicketEndpoint(s.service.LinkTicket))
s.ApiGroup.GET("/automations", s.RoleAuth([]role.Role{role.AutomationRead}), automations.ListAutomationsEndpoint(s.service.ListAutomations))
s.ApiGroup.GET("/jobs", s.RoleAuth([]role.Role{role.JobRead}), jobs.ListJobsEndpoint(s.service.ListJobs))
s.ApiGroup.GET("/playbooks", s.RoleAuth([]role.Role{role.PlaybookRead}), playbooks.ListPlaybooksEndpoint(s.service.ListPlaybooks))
s.ApiGroup.GET("/tasks", s.RoleAuth([]role.Role{role.TicketRead}), tasks.ListTasksEndpoint(s.service.ListTasks))
s.ApiGroup.GET("/templates", s.RoleAuth([]role.Role{role.TemplateRead}), templates.ListTemplatesEndpoint(s.service.ListTemplates))
s.ApiGroup.GET("/tickettypes", s.RoleAuth([]role.Role{role.TickettypeRead}), tickettypes.ListTicketTypesEndpoint(s.service.ListTicketTypes))
s.ApiGroup.GET("/tickets", s.RoleAuth([]role.Role{role.TicketRead}), tickets.ListTicketsEndpoint(s.service.ListTickets))
s.ApiGroup.GET("/userdata", s.RoleAuth([]role.Role{role.UserdataRead}), userdata.ListUserDataEndpoint(s.service.ListUserData))
s.ApiGroup.GET("/users", s.RoleAuth([]role.Role{role.UserRead}), users.ListUsersEndpoint(s.service.ListUsers))
s.ApiGroup.DELETE("/tickets/:id/artifacts/:name", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RemoveArtifactEndpoint(s.service.RemoveArtifact))
s.ApiGroup.DELETE("/tickets/:id/comments/:commentID", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RemoveCommentEndpoint(s.service.RemoveComment))
s.ApiGroup.DELETE("/tickets/:id/playbooks/:playbookID", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RemoveTicketPlaybookEndpoint(s.service.RemoveTicketPlaybook))
s.ApiGroup.POST("/tickets/:id/artifacts/:name/run/:automation", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RunArtifactEndpoint(s.service.RunArtifact))
s.ApiGroup.POST("/jobs", s.RoleAuth([]role.Role{role.JobWrite}), jobs.RunJobEndpoint(s.service.RunJob))
s.ApiGroup.POST("/tickets/:id/playbooks/:playbookID/task/:taskID/run", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.RunTaskEndpoint(s.service.RunTask))
s.ApiGroup.PUT("/tickets/:id/artifacts/:name", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetArtifactEndpoint(s.service.SetArtifact))
s.ApiGroup.PUT("/tickets/:id/references", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetReferencesEndpoint(s.service.SetReferences))
s.ApiGroup.PUT("/tickets/:id/schema", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetSchemaEndpoint(s.service.SetSchema))
s.ApiGroup.PUT("/tickets/:id/playbooks/:playbookID/task/:taskID", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.SetTaskEndpoint(s.service.SetTask))
s.ApiGroup.DELETE("/tickets/:id/tickets", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.UnlinkTicketEndpoint(s.service.UnlinkTicket))
s.ApiGroup.PUT("/automations/:id", s.RoleAuth([]role.Role{role.AutomationWrite}), automations.UpdateAutomationEndpoint(s.service.UpdateAutomation))
s.ApiGroup.PUT("/currentuserdata", s.RoleAuth([]role.Role{role.CurrentuserdataWrite}), userdata.UpdateCurrentUserDataEndpoint(s.service.UpdateCurrentUserData))
s.ApiGroup.PUT("/jobs/:id", s.RoleAuth([]role.Role{role.JobWrite}), jobs.UpdateJobEndpoint(s.service.UpdateJob))
s.ApiGroup.PUT("/playbooks/:id", s.RoleAuth([]role.Role{role.PlaybookWrite}), playbooks.UpdatePlaybookEndpoint(s.service.UpdatePlaybook))
s.ApiGroup.PUT("/templates/:id", s.RoleAuth([]role.Role{role.TemplateWrite}), templates.UpdateTemplateEndpoint(s.service.UpdateTemplate))
s.ApiGroup.PUT("/tickets/:id", s.RoleAuth([]role.Role{role.TicketWrite}), tickets.UpdateTicketEndpoint(s.service.UpdateTicket))
s.ApiGroup.PUT("/tickettypes/:id", s.RoleAuth([]role.Role{role.TickettypeWrite}), tickettypes.UpdateTicketTypeEndpoint(s.service.UpdateTicketType))
s.ApiGroup.PUT("/users/:id", s.RoleAuth([]role.Role{role.UserWrite}), users.UpdateUserEndpoint(s.service.UpdateUser))
s.ApiGroup.PUT("/userdata/:id", s.RoleAuth([]role.Role{role.UserdataWrite}), userdata.UpdateUserDataEndpoint(s.service.UpdateUserData))
}
// run the Server. It will listen on either HTTP or HTTPS depending on the
// config passed to NewServer.
func (s *Server) run() error {
log.Printf("Serving on address %s\n", s.server.Addr)
if s.config.InsecureHTTP {
return s.server.ListenAndServe()
}
return s.server.ListenAndServeTLS(s.config.TLSCertFile, s.config.TLSKeyFile)
}
// Shutdown will gracefully shutdown the Server.
func (s *Server) Shutdown() error {
return s.server.Shutdown(context.Background())
}
// RunWithSigHandler runs the Server with SIGTERM handling automatically
// enabled. The server will listen for a SIGTERM signal and gracefully shutdown
// the web server.
// It's possible to optionally pass any number shutdown functions which will
// execute one by one after the webserver has been shutdown successfully.
func (s *Server) RunWithSigHandler(shutdown ...func() error) error {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigCh
s.Shutdown()
}()
err := s.run()
if err != nil {
if err != http.ErrServerClosed {
return err
}
}
for _, fn := range shutdown {
err := fn()
if err != nil {
return err
}
}
return nil
}

View File

@@ -1,6 +0,0 @@
package api
type Response struct {
Code int
Body interface{}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,90 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreateAutomationEndpoint executes the core logic of the related
// route endpoint.
func CreateAutomationEndpoint(handler func(ctx context.Context, params *CreateAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreateAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreateAutomationParams creates a new CreateAutomationParams object
// with the default values initialized.
func NewCreateAutomationParams() *CreateAutomationParams {
var ()
return &CreateAutomationParams{}
}
// CreateAutomationParams contains all the bound params for the create automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters createAutomation
type CreateAutomationParams struct {
/*New automation
Required: true
In: body
*/
Automation *models.AutomationForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreateAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.AutomationForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("automation", "body", ""))
} else {
res = append(res, errors.NewParseError("automation", "body", "", err))
}
} else {
o.Automation = &body
}
} else {
res = append(res, errors.Required("automation", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,87 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeleteAutomationEndpoint executes the core logic of the related
// route endpoint.
func DeleteAutomationEndpoint(handler func(ctx context.Context, params *DeleteAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeleteAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeleteAutomationParams creates a new DeleteAutomationParams object
// with the default values initialized.
func NewDeleteAutomationParams() *DeleteAutomationParams {
var ()
return &DeleteAutomationParams{}
}
// DeleteAutomationParams contains all the bound params for the delete automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters deleteAutomation
type DeleteAutomationParams struct {
/*Automation ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeleteAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeleteAutomationParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetAutomationEndpoint executes the core logic of the related
// route endpoint.
func GetAutomationEndpoint(handler func(ctx context.Context, params *GetAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetAutomationParams creates a new GetAutomationParams object
// with the default values initialized.
func NewGetAutomationParams() *GetAutomationParams {
var ()
return &GetAutomationParams{}
}
// GetAutomationParams contains all the bound params for the get automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters getAutomation
type GetAutomationParams struct {
/*Automation ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetAutomationParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListAutomationsEndpoint executes the core logic of the related
// route endpoint.
func ListAutomationsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListAutomationsParams creates a new ListAutomationsParams object
// with the default values initialized.
func NewListAutomationsParams() *ListAutomationsParams {
var ()
return &ListAutomationsParams{}
}
// ListAutomationsParams contains all the bound params for the list automations operation
// typically these are obtained from a http.Request
//
// swagger:parameters listAutomations
type ListAutomationsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListAutomationsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package automations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateAutomationEndpoint executes the core logic of the related
// route endpoint.
func UpdateAutomationEndpoint(handler func(ctx context.Context, params *UpdateAutomationParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateAutomationParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateAutomationParams creates a new UpdateAutomationParams object
// with the default values initialized.
func NewUpdateAutomationParams() *UpdateAutomationParams {
var ()
return &UpdateAutomationParams{}
}
// UpdateAutomationParams contains all the bound params for the update automation operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateAutomation
type UpdateAutomationParams struct {
/*Automation object that needs to be added
Required: true
In: body
*/
Automation *models.AutomationForm
/*Automation ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateAutomationParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.AutomationForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("automation", "body", ""))
} else {
res = append(res, errors.NewParseError("automation", "body", "", err))
}
} else {
o.Automation = &body
}
} else {
res = append(res, errors.Required("automation", "body", ""))
}
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateAutomationParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetJobEndpoint executes the core logic of the related
// route endpoint.
func GetJobEndpoint(handler func(ctx context.Context, params *GetJobParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetJobParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetJobParams creates a new GetJobParams object
// with the default values initialized.
func NewGetJobParams() *GetJobParams {
var ()
return &GetJobParams{}
}
// GetJobParams contains all the bound params for the get job operation
// typically these are obtained from a http.Request
//
// swagger:parameters getJob
type GetJobParams struct {
/*Job ID
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetJobParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetJobParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListJobsEndpoint executes the core logic of the related
// route endpoint.
func ListJobsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListJobsParams creates a new ListJobsParams object
// with the default values initialized.
func NewListJobsParams() *ListJobsParams {
var ()
return &ListJobsParams{}
}
// ListJobsParams contains all the bound params for the list jobs operation
// typically these are obtained from a http.Request
//
// swagger:parameters listJobs
type ListJobsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListJobsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,90 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// RunJobEndpoint executes the core logic of the related
// route endpoint.
func RunJobEndpoint(handler func(ctx context.Context, params *RunJobParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewRunJobParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewRunJobParams creates a new RunJobParams object
// with the default values initialized.
func NewRunJobParams() *RunJobParams {
var ()
return &RunJobParams{}
}
// RunJobParams contains all the bound params for the run job operation
// typically these are obtained from a http.Request
//
// swagger:parameters runJob
type RunJobParams struct {
/*New job
Required: true
In: body
*/
Job *models.JobForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *RunJobParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.JobForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("job", "body", ""))
} else {
res = append(res, errors.NewParseError("job", "body", "", err))
}
} else {
o.Job = &body
}
} else {
res = append(res, errors.Required("job", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package jobs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdateJobEndpoint executes the core logic of the related
// route endpoint.
func UpdateJobEndpoint(handler func(ctx context.Context, params *UpdateJobParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdateJobParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdateJobParams creates a new UpdateJobParams object
// with the default values initialized.
func NewUpdateJobParams() *UpdateJobParams {
var ()
return &UpdateJobParams{}
}
// UpdateJobParams contains all the bound params for the update job operation
// typically these are obtained from a http.Request
//
// swagger:parameters updateJob
type UpdateJobParams struct {
/*Job ID
Required: true
In: path
*/
ID string
/*Job object that needs to be added
Required: true
In: body
*/
Job *models.Job
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdateJobParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.Job
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("job", "body", ""))
} else {
res = append(res, errors.NewParseError("job", "body", "", err))
}
} else {
o.Job = &body
}
} else {
res = append(res, errors.Required("job", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdateJobParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package logs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetLogsEndpoint executes the core logic of the related
// route endpoint.
func GetLogsEndpoint(handler func(ctx context.Context, params *GetLogsParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetLogsParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetLogsParams creates a new GetLogsParams object
// with the default values initialized.
func NewGetLogsParams() *GetLogsParams {
var ()
return &GetLogsParams{}
}
// GetLogsParams contains all the bound params for the get logs operation
// typically these are obtained from a http.Request
//
// swagger:parameters getLogs
type GetLogsParams struct {
/*Reference
Required: true
In: path
*/
Reference string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetLogsParams) ReadRequest(ctx *gin.Context) error {
var res []error
rReference := []string{ctx.Param("reference")}
if err := o.bindReference(rReference, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetLogsParams) bindReference(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.Reference = raw
return nil
}

View File

@@ -1,90 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// CreatePlaybookEndpoint executes the core logic of the related
// route endpoint.
func CreatePlaybookEndpoint(handler func(ctx context.Context, params *CreatePlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewCreatePlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewCreatePlaybookParams creates a new CreatePlaybookParams object
// with the default values initialized.
func NewCreatePlaybookParams() *CreatePlaybookParams {
var ()
return &CreatePlaybookParams{}
}
// CreatePlaybookParams contains all the bound params for the create playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters createPlaybook
type CreatePlaybookParams struct {
/*New playbook
Required: true
In: body
*/
Playbook *models.PlaybookTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *CreatePlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
if runtime.HasBody(ctx.Request) {
var body models.PlaybookTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("playbook", "body", ""))
} else {
res = append(res, errors.NewParseError("playbook", "body", "", err))
}
} else {
o.Playbook = &body
}
} else {
res = append(res, errors.Required("playbook", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,87 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// DeletePlaybookEndpoint executes the core logic of the related
// route endpoint.
func DeletePlaybookEndpoint(handler func(ctx context.Context, params *DeletePlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewDeletePlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewDeletePlaybookParams creates a new DeletePlaybookParams object
// with the default values initialized.
func NewDeletePlaybookParams() *DeletePlaybookParams {
var ()
return &DeletePlaybookParams{}
}
// DeletePlaybookParams contains all the bound params for the delete playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters deletePlaybook
type DeletePlaybookParams struct {
/*Playbook name
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *DeletePlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *DeletePlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,87 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetPlaybookEndpoint executes the core logic of the related
// route endpoint.
func GetPlaybookEndpoint(handler func(ctx context.Context, params *GetPlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewGetPlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetPlaybookParams creates a new GetPlaybookParams object
// with the default values initialized.
func NewGetPlaybookParams() *GetPlaybookParams {
var ()
return &GetPlaybookParams{}
}
// GetPlaybookParams contains all the bound params for the get playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters getPlaybook
type GetPlaybookParams struct {
/*Playbook name
Required: true
In: path
*/
ID string
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetPlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *GetPlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// ListPlaybooksEndpoint executes the core logic of the related
// route endpoint.
func ListPlaybooksEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewListPlaybooksParams creates a new ListPlaybooksParams object
// with the default values initialized.
func NewListPlaybooksParams() *ListPlaybooksParams {
var ()
return &ListPlaybooksParams{}
}
// ListPlaybooksParams contains all the bound params for the list playbooks operation
// typically these are obtained from a http.Request
//
// swagger:parameters listPlaybooks
type ListPlaybooksParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *ListPlaybooksParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,111 +0,0 @@
package playbooks
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"io"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/SecurityBrewery/catalyst/generated/models"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// UpdatePlaybookEndpoint executes the core logic of the related
// route endpoint.
func UpdatePlaybookEndpoint(handler func(ctx context.Context, params *UpdatePlaybookParams) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
// generate params from request
params := NewUpdatePlaybookParams()
err := params.ReadRequest(ctx)
if err != nil {
errObj := err.(*errors.CompositeError)
ctx.Writer.Header().Set("Content-Type", "application/problem+json")
ctx.JSON(int(errObj.Code()), gin.H{"error": errObj.Error()})
return
}
resp := handler(ctx, params)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewUpdatePlaybookParams creates a new UpdatePlaybookParams object
// with the default values initialized.
func NewUpdatePlaybookParams() *UpdatePlaybookParams {
var ()
return &UpdatePlaybookParams{}
}
// UpdatePlaybookParams contains all the bound params for the update playbook operation
// typically these are obtained from a http.Request
//
// swagger:parameters updatePlaybook
type UpdatePlaybookParams struct {
/*Playbook ID
Required: true
In: path
*/
ID string
/*Updated playbook
Required: true
In: body
*/
Playbook *models.PlaybookTemplateForm
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UpdatePlaybookParams) ReadRequest(ctx *gin.Context) error {
var res []error
rID := []string{ctx.Param("id")}
if err := o.bindID(rID, true); err != nil {
res = append(res, err)
}
if runtime.HasBody(ctx.Request) {
var body models.PlaybookTemplateForm
if err := ctx.BindJSON(&body); err != nil {
if err == io.EOF {
res = append(res, errors.Required("playbook", "body", ""))
} else {
res = append(res, errors.NewParseError("playbook", "body", "", err))
}
} else {
o.Playbook = &body
}
} else {
res = append(res, errors.Required("playbook", "body", ""))
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (o *UpdatePlaybookParams) bindID(rawData []string, hasKey bool) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
o.ID = raw
return nil
}

View File

@@ -1,55 +0,0 @@
package settings
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-openapi/errors"
"github.com/SecurityBrewery/catalyst/generated/restapi/api"
)
// GetSettingsEndpoint executes the core logic of the related
// route endpoint.
func GetSettingsEndpoint(handler func(ctx context.Context) *api.Response) gin.HandlerFunc {
return func(ctx *gin.Context) {
resp := handler(ctx)
switch resp.Code {
case http.StatusNoContent:
ctx.AbortWithStatus(resp.Code)
default:
ctx.JSON(resp.Code, resp.Body)
}
}
}
// NewGetSettingsParams creates a new GetSettingsParams object
// with the default values initialized.
func NewGetSettingsParams() *GetSettingsParams {
var ()
return &GetSettingsParams{}
}
// GetSettingsParams contains all the bound params for the get settings operation
// typically these are obtained from a http.Request
//
// swagger:parameters getSettings
type GetSettingsParams struct {
}
// ReadRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *GetSettingsParams) ReadRequest(ctx *gin.Context) error {
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

Some files were not shown because too many files have changed in this diff Show More