checkpoint - phase 13 complete
This commit is contained in:
parent
ad5a7e5f7a
commit
3fd9f77335
|
|
@ -0,0 +1,40 @@
|
|||
# ©AngelaMos | 2026
|
||||
# .env.example
|
||||
|
||||
# Application
|
||||
ENV=development
|
||||
DEBUG=true
|
||||
HOST=0.0.0.0
|
||||
PORT=8000
|
||||
LOG_LEVEL=INFO
|
||||
API_KEY=changeme-generate-a-real-key
|
||||
|
||||
# Docker Host Ports (change these if you have conflicts)
|
||||
POSTGRES_HOST_PORT=16969
|
||||
REDIS_HOST_PORT=26969
|
||||
BACKEND_HOST_PORT=36969
|
||||
|
||||
# PostgreSQL
|
||||
POSTGRES_DB=angelusvigil
|
||||
POSTGRES_USER=vigil
|
||||
POSTGRES_PASSWORD=change-this-password
|
||||
DATABASE_URL=postgresql+asyncpg://vigil:change-this-password@postgres:5432/angelusvigil
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://redis:6379
|
||||
|
||||
# GeoIP (MaxMind - register at https://www.maxmind.com/en/geolite2/signup)
|
||||
GEOIP_ACCOUNT_ID=
|
||||
GEOIP_LICENSE_KEY=
|
||||
GEOIP_DB_PATH=/usr/share/GeoIP/GeoLite2-City.mmdb
|
||||
|
||||
# Nginx Log Path (inside container)
|
||||
NGINX_LOG_PATH=/var/log/nginx/access.log
|
||||
|
||||
# Pipeline Tuning
|
||||
RAW_QUEUE_SIZE=1000
|
||||
PARSED_QUEUE_SIZE=500
|
||||
FEATURE_QUEUE_SIZE=200
|
||||
ALERT_QUEUE_SIZE=100
|
||||
BATCH_SIZE=32
|
||||
BATCH_TIMEOUT_MS=50
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
# ©AngelaMos | 2026
|
||||
# .gitignore
|
||||
|
||||
# Planning docs
|
||||
.angelusvigil/
|
||||
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
venv/
|
||||
.venv/
|
||||
ENV/
|
||||
env/
|
||||
|
||||
# Testing
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Docker
|
||||
docker-compose.override.yml
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
# Runtime data
|
||||
data/models/
|
||||
data/geoip/
|
||||
data/sample-logs/*.log
|
||||
|
||||
# MLflow
|
||||
mlruns/
|
||||
mlartifacts/
|
||||
|
|
@ -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/>.
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
# AngelusVigil
|
||||
|
||||
IN PROGRESS
|
||||
|
||||
AI-powered threat detection engine that analyzes web server access logs using machine learning to classify HTTP traffic as benign or malicious in real-time.
|
||||
|
||||
Deploys as a Docker sidecar alongside any nginx-based infrastructure. Zero code changes to the monitored application.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|-----------|
|
||||
| API | FastAPI (async) |
|
||||
| ML | PyTorch autoencoder + scikit-learn (RF + IF) |
|
||||
| Inference | ONNX Runtime (CPU) |
|
||||
| Database | PostgreSQL 18 |
|
||||
| Cache | Redis 7.4 |
|
||||
| GeoIP | MaxMind GeoLite2 |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
just setup
|
||||
just dev-up
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
3-model ensemble (autoencoder + Random Forest + Isolation Forest) scores each request through a weighted fusion producing a unified threat score [0.0, 1.0]:
|
||||
|
||||
- **HIGH** (0.7+): Store + alert + block recommendation
|
||||
- **MEDIUM** (0.5-0.7): Store + monitor
|
||||
- **LOW** (<0.5): Log only
|
||||
|
||||
See `learn/` for detailed documentation.
|
||||
|
||||
## License
|
||||
|
||||
AGPLv3 - See [LICENSE](LICENSE)
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
# ©AngelaMos | 2026
|
||||
# alembic.ini
|
||||
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
sqlalchemy.url = postgresql+asyncpg://vigil:changeme@localhost:5432/angelusvigil
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
env.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from app.config import settings
|
||||
from app.models import ModelMetadata, ThreatEvent
|
||||
|
||||
_ = (ModelMetadata, ThreatEvent)
|
||||
|
||||
target_metadata = SQLModel.metadata
|
||||
config = context.config
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""
|
||||
Run migrations in offline mode for SQL script generation.
|
||||
"""
|
||||
context.configure(
|
||||
url=settings.database_url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection) -> None:
|
||||
"""
|
||||
Execute migrations against a synchronous connection.
|
||||
"""
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_migrations_online() -> None:
|
||||
"""
|
||||
Run migrations in online mode using an async engine.
|
||||
"""
|
||||
engine = create_async_engine(
|
||||
settings.database_url,
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with engine.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
asyncio.run(run_migrations_online())
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel
|
||||
${imports if imports else ""}
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
initial schema
|
||||
|
||||
Revision ID: 65c8ac60f6f6
|
||||
Revises:
|
||||
Create Date: 2026-02-11 17:43:24.263837
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel
|
||||
|
||||
revision: str = "65c8ac60f6f6"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"threat_events",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"source_ip", sqlmodel.sql.sqltypes.AutoString(length=45), nullable=False
|
||||
),
|
||||
sa.Column(
|
||||
"request_method",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=10),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"request_path", sqlmodel.sql.sqltypes.AutoString(), nullable=False
|
||||
),
|
||||
sa.Column("status_code", sa.SmallInteger(), nullable=False),
|
||||
sa.Column("response_size", sa.Integer(), nullable=False),
|
||||
sa.Column(
|
||||
"user_agent", sqlmodel.sql.sqltypes.AutoString(), nullable=False
|
||||
),
|
||||
sa.Column("threat_score", sa.Float(), nullable=False),
|
||||
sa.Column(
|
||||
"severity", sqlmodel.sql.sqltypes.AutoString(length=6), nullable=False
|
||||
),
|
||||
sa.Column("component_scores", sa.JSON(), nullable=False),
|
||||
sa.Column(
|
||||
"geo_country",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=2),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
"geo_city",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=255),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("geo_lat", sa.Float(), nullable=True),
|
||||
sa.Column("geo_lon", sa.Float(), nullable=True),
|
||||
sa.Column("feature_vector", sa.JSON(), nullable=False),
|
||||
sa.Column("matched_rules", sa.JSON(), nullable=True),
|
||||
sa.Column(
|
||||
"model_version",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=64),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("reviewed", sa.Boolean(), nullable=False),
|
||||
sa.Column(
|
||||
"review_label",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=20),
|
||||
nullable=True,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
|
||||
op.create_index("idx_threat_events_created_at", "threat_events", ["created_at"])
|
||||
op.create_index("idx_threat_events_source_ip", "threat_events", ["source_ip"])
|
||||
op.create_index("idx_threat_events_severity", "threat_events", ["severity"])
|
||||
op.create_index("idx_threat_events_score", "threat_events", ["threat_score"])
|
||||
op.create_index(
|
||||
"idx_threat_events_reviewed",
|
||||
"threat_events",
|
||||
["reviewed"],
|
||||
postgresql_where=sa.text("reviewed = FALSE"),
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"model_metadata",
|
||||
sa.Column("id", sa.Uuid(), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"model_type",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=30),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"version", sqlmodel.sql.sqltypes.AutoString(length=64), nullable=False
|
||||
),
|
||||
sa.Column("training_samples", sa.Integer(), nullable=False),
|
||||
sa.Column("metrics", sa.JSON(), nullable=False),
|
||||
sa.Column(
|
||||
"artifact_path", sqlmodel.sql.sqltypes.AutoString(), nullable=False
|
||||
),
|
||||
sa.Column("is_active", sa.Boolean(), nullable=False),
|
||||
sa.Column(
|
||||
"mlflow_run_id",
|
||||
sqlmodel.sql.sqltypes.AutoString(length=64),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column("threshold", sa.Float(), nullable=True),
|
||||
sa.Column("notes", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
|
||||
op.create_index(
|
||||
"idx_model_metadata_active",
|
||||
"model_metadata",
|
||||
["model_type"],
|
||||
unique=True,
|
||||
postgresql_where=sa.text("is_active = TRUE"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("idx_model_metadata_active", table_name="model_metadata")
|
||||
op.drop_table("model_metadata")
|
||||
|
||||
op.drop_index("idx_threat_events_reviewed", table_name="threat_events")
|
||||
op.drop_index("idx_threat_events_score", table_name="threat_events")
|
||||
op.drop_index("idx_threat_events_severity", table_name="threat_events")
|
||||
op.drop_index("idx_threat_events_source_ip", table_name="threat_events")
|
||||
op.drop_index("idx_threat_events_created_at", table_name="threat_events")
|
||||
op.drop_table("threat_events")
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
|
||||
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
|
||||
⠀⠀⠀⠀⠀⠀⣄⠀⠀⠀⣦⣤⣾⣿⠿⠛⣋⣥⣤⣀⠀⠀⠀⠀
|
||||
⠀⠀⠀⠀⡤⡀⢈⢻⣬⣿⠟⢁⣤⣶⣿⣿⡿⠿⠿⠛⠛⢀⣄⠀
|
||||
⠀⠀⢢⣘⣿⣿⣶⣿⣯⣤⣾⣿⣿⣿⠟⠁⠄⠀⣾⡇⣼⢻⣿⣾
|
||||
⣰⠞⠛⢉⣩⣿⣿⣿⣿⣿⣿⣿⣿⠋⣼⣧⣤⣴⠟⣠⣿⢰⣿⣿
|
||||
⣶⡾⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣈⣩⣤⡶⠟⢛⣩⣴⣿⣿⡟
|
||||
⣠⣄⠈⠀⣰⡦⠙⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⡛⠛⠛⠁
|
||||
⣉⠛⠛⠛⣁⡔⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠥⠀⠀
|
||||
⣭⣏⣭⣭⣥⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢠
|
||||
"""
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__main__.py
|
||||
"""
|
||||
|
||||
import uvicorn
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""
|
||||
Run the AngelusVigil API server
|
||||
"""
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
reload=settings.debug,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
health.py
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Request, Response
|
||||
|
||||
from app.core.redis_manager import redis_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health(request: Request) -> dict:
|
||||
"""
|
||||
Liveness probe — returns 200 if the process is alive.
|
||||
"""
|
||||
uptime = time.monotonic() - request.app.state.startup_time
|
||||
return {
|
||||
"status": "healthy",
|
||||
"uptime_seconds": round(uptime, 2),
|
||||
"pipeline_running": request.app.state.pipeline_running,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/ready")
|
||||
async def ready(request: Request, response: Response) -> dict:
|
||||
"""
|
||||
Readiness probe — checks all service dependencies.
|
||||
"""
|
||||
redis_ok = await _check_redis()
|
||||
database_ok = await _check_database(request)
|
||||
|
||||
checks = {
|
||||
"database": "ok" if database_ok else "error",
|
||||
"redis": "ok" if redis_ok else "error",
|
||||
"models_loaded": getattr(request.app.state, "models_loaded", False),
|
||||
}
|
||||
|
||||
all_ok = database_ok and redis_ok
|
||||
|
||||
if not all_ok:
|
||||
response.status_code = 503
|
||||
|
||||
return {
|
||||
"status": "ready" if all_ok else "not_ready",
|
||||
"checks": checks,
|
||||
}
|
||||
|
||||
|
||||
async def _check_redis() -> bool:
|
||||
"""
|
||||
Ping Redis and return connectivity status.
|
||||
"""
|
||||
return await redis_manager.ping()
|
||||
|
||||
|
||||
async def _check_database(request: Request) -> bool:
|
||||
"""
|
||||
Verify database engine is connected and responsive.
|
||||
"""
|
||||
engine = getattr(request.app.state, "db_engine", None)
|
||||
if engine is None:
|
||||
return False
|
||||
try:
|
||||
async with engine.connect() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
config.py
|
||||
"""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""
|
||||
Application configuration loaded from environment variables.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
case_sensitive=False,
|
||||
)
|
||||
|
||||
app_name: str = "AngelusVigil"
|
||||
env: str = "development"
|
||||
debug: bool = False
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8000
|
||||
api_key: str = ""
|
||||
log_level: str = "INFO"
|
||||
|
||||
database_url: str = (
|
||||
"postgresql+asyncpg://vigil:changeme@localhost:5432/angelusvigil"
|
||||
)
|
||||
|
||||
redis_url: str = "redis://localhost:6379"
|
||||
|
||||
geoip_db_path: str = "/usr/share/GeoIP/GeoLite2-City.mmdb"
|
||||
|
||||
nginx_log_path: str = "/var/log/nginx/access.log"
|
||||
|
||||
raw_queue_size: int = 1000
|
||||
parsed_queue_size: int = 500
|
||||
feature_queue_size: int = 200
|
||||
alert_queue_size: int = 100
|
||||
|
||||
batch_size: int = 32
|
||||
batch_timeout_ms: int = 50
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
rules.py
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import NamedTuple
|
||||
|
||||
from app.core.features.patterns import (
|
||||
COMMAND_INJECTION,
|
||||
DOUBLE_ENCODED,
|
||||
FILE_INCLUSION,
|
||||
PATH_TRAVERSAL,
|
||||
SQLI,
|
||||
XSS,
|
||||
)
|
||||
from app.core.features.signatures import SCANNER_USER_AGENTS
|
||||
from app.core.ingestion.parsers import ParsedLogEntry
|
||||
|
||||
|
||||
class _PatternRule(NamedTuple):
|
||||
"""
|
||||
A regex-based detection rule applied to the request URI.
|
||||
"""
|
||||
name: str
|
||||
pattern: object
|
||||
score: float
|
||||
|
||||
|
||||
class _ThresholdRule(NamedTuple):
|
||||
"""
|
||||
A threshold-based detection rule applied to a windowed feature.
|
||||
"""
|
||||
name: str
|
||||
feature_key: str
|
||||
threshold: float
|
||||
score: float
|
||||
|
||||
|
||||
_PATTERN_RULES: list[_PatternRule] = [
|
||||
_PatternRule("COMMAND_INJECTION", COMMAND_INJECTION, 0.90),
|
||||
_PatternRule("SQL_INJECTION", SQLI, 0.85),
|
||||
_PatternRule("XSS", XSS, 0.80),
|
||||
_PatternRule("FILE_INCLUSION", FILE_INCLUSION, 0.75),
|
||||
_PatternRule("PATH_TRAVERSAL", PATH_TRAVERSAL, 0.60),
|
||||
]
|
||||
|
||||
_THRESHOLD_RULES: list[_ThresholdRule] = [
|
||||
_ThresholdRule("RATE_ANOMALY", "req_count_1m", 100.0, 0.30),
|
||||
_ThresholdRule("HIGH_ERROR_RATE", "error_rate_5m", 0.5, 0.25),
|
||||
]
|
||||
|
||||
_DOUBLE_ENCODING_SCORE = 0.40
|
||||
_SCANNER_UA_SCORE = 0.35
|
||||
_BOOST_PER_ADDITIONAL_RULE = 0.05
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RuleResult:
|
||||
"""
|
||||
Output of the rule-based detection engine for a single request.
|
||||
"""
|
||||
threat_score: float
|
||||
severity: str
|
||||
matched_rules: list[str] = field(default_factory=list)
|
||||
component_scores: dict[str, float] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _classify_severity(score: float) -> str:
|
||||
"""
|
||||
Map a threat score to a severity label.
|
||||
"""
|
||||
if score >= 0.7:
|
||||
return "HIGH"
|
||||
if score >= 0.5:
|
||||
return "MEDIUM"
|
||||
return "LOW"
|
||||
|
||||
|
||||
class RuleEngine:
|
||||
"""
|
||||
Cold-start rule-based detection engine inspired by ModSecurity CRS.
|
||||
Scores requests using pattern matching, signature detection,
|
||||
and behavioral thresholds from windowed features.
|
||||
"""
|
||||
|
||||
def score_request(
|
||||
self,
|
||||
features: dict[str, int | float | bool | str],
|
||||
entry: ParsedLogEntry,
|
||||
) -> RuleResult:
|
||||
"""
|
||||
Evaluate all rules against a request and return a composite score.
|
||||
"""
|
||||
matched: list[tuple[str, float]] = []
|
||||
|
||||
uri = entry.path
|
||||
if entry.query_string:
|
||||
uri = f"{entry.path}?{entry.query_string}"
|
||||
|
||||
for rule in _PATTERN_RULES:
|
||||
if rule.pattern.search(uri):
|
||||
matched.append((rule.name, rule.score))
|
||||
|
||||
if DOUBLE_ENCODED.search(uri):
|
||||
matched.append(("DOUBLE_ENCODING", _DOUBLE_ENCODING_SCORE))
|
||||
|
||||
ua_lower = entry.user_agent.lower()
|
||||
if any(sig in ua_lower for sig in SCANNER_USER_AGENTS):
|
||||
matched.append(("SCANNER_UA", _SCANNER_UA_SCORE))
|
||||
|
||||
for rule in _THRESHOLD_RULES:
|
||||
value = features.get(rule.feature_key, 0)
|
||||
if isinstance(value, (int, float)) and value > rule.threshold:
|
||||
matched.append((rule.name, rule.score))
|
||||
|
||||
if not matched:
|
||||
return RuleResult(threat_score=0.0, severity="LOW")
|
||||
|
||||
scores = sorted([s for _, s in matched], reverse=True)
|
||||
threat_score = min(
|
||||
scores[0] + _BOOST_PER_ADDITIONAL_RULE * (len(scores) - 1),
|
||||
1.0,
|
||||
)
|
||||
|
||||
return RuleResult(
|
||||
threat_score=threat_score,
|
||||
severity=_classify_severity(threat_score),
|
||||
matched_rules=[name for name, _ in matched],
|
||||
component_scores={name: score for name, score in matched},
|
||||
)
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
geoip.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import ipaddress
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import geoip2.database
|
||||
from geoip2.errors import AddressNotFoundError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GeoResult:
|
||||
"""
|
||||
Structured GeoIP lookup result.
|
||||
"""
|
||||
country: str | None
|
||||
city: str | None
|
||||
lat: float | None
|
||||
lon: float | None
|
||||
|
||||
|
||||
class GeoIPService:
|
||||
"""
|
||||
Async GeoIP lookup service backed by a local MaxMind GeoLite2-City database.
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str) -> None:
|
||||
self._reader: geoip2.database.Reader | None = None
|
||||
self._db_path = db_path
|
||||
|
||||
if Path(db_path).is_file():
|
||||
self._reader = geoip2.database.Reader(db_path)
|
||||
logger.info("GeoIP database loaded from %s", db_path)
|
||||
else:
|
||||
logger.warning("GeoIP database not found at %s — lookups disabled", db_path)
|
||||
|
||||
async def lookup(self, ip: str) -> GeoResult | None:
|
||||
"""
|
||||
Look up geographic data for an IP address.
|
||||
Returns None for private IPs, unknown addresses, or when no database is loaded.
|
||||
"""
|
||||
if self._reader is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
if ipaddress.ip_address(ip).is_private:
|
||||
return None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
try:
|
||||
response = await asyncio.to_thread(self._reader.city, ip)
|
||||
except AddressNotFoundError:
|
||||
return None
|
||||
|
||||
return GeoResult(
|
||||
country=response.country.iso_code,
|
||||
city=response.city.name,
|
||||
lat=response.location.latitude,
|
||||
lon=response.location.longitude,
|
||||
)
|
||||
|
||||
def swap_reader(self, new_path: str) -> None:
|
||||
"""
|
||||
Atomically replace the database reader after a .mmdb file update.
|
||||
"""
|
||||
old_reader = self._reader
|
||||
self._reader = geoip2.database.Reader(new_path)
|
||||
self._db_path = new_path
|
||||
logger.info("GeoIP reader swapped to %s", new_path)
|
||||
|
||||
if old_reader is not None:
|
||||
old_reader.close()
|
||||
|
||||
def close(self) -> None:
|
||||
"""
|
||||
Close the underlying database reader.
|
||||
"""
|
||||
if self._reader is not None:
|
||||
self._reader.close()
|
||||
self._reader = None
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,206 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
aggregator.py
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
from collections import Counter
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
|
||||
WINDOW_1M = 60
|
||||
WINDOW_5M = 300
|
||||
WINDOW_10M = 600
|
||||
KEY_TTL = 900
|
||||
|
||||
|
||||
def _hash_member(value: str) -> str:
|
||||
"""
|
||||
Produce a compact 16-char hex digest for sorted set deduplication.
|
||||
"""
|
||||
return hashlib.md5(value.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
class WindowAggregator:
|
||||
"""
|
||||
Per-IP sliding window feature aggregator backed by Redis sorted sets.
|
||||
"""
|
||||
|
||||
def __init__(self, redis_client: aioredis.Redis) -> None:
|
||||
self._redis = redis_client
|
||||
|
||||
async def record_and_aggregate(
|
||||
self,
|
||||
ip: str,
|
||||
request_id: str,
|
||||
path: str,
|
||||
path_depth: int,
|
||||
method: str,
|
||||
status_code: int,
|
||||
user_agent: str,
|
||||
response_size: int,
|
||||
timestamp: float,
|
||||
) -> dict[str, float]:
|
||||
"""
|
||||
Record a request into Redis sorted sets and return all 12
|
||||
per-IP windowed features.
|
||||
"""
|
||||
prefix = f"ip:{ip}"
|
||||
keys = {
|
||||
"requests": f"{prefix}:requests",
|
||||
"paths": f"{prefix}:paths",
|
||||
"statuses": f"{prefix}:statuses",
|
||||
"uas": f"{prefix}:uas",
|
||||
"sizes": f"{prefix}:sizes",
|
||||
"methods": f"{prefix}:methods",
|
||||
"depths": f"{prefix}:depths",
|
||||
}
|
||||
|
||||
trim_boundary = timestamp - KEY_TTL
|
||||
w1m = timestamp - WINDOW_1M
|
||||
w5m = timestamp - WINDOW_5M
|
||||
w10m = timestamp - WINDOW_10M
|
||||
|
||||
pipe = self._redis.pipeline()
|
||||
|
||||
pipe.zadd(keys["requests"], {request_id: timestamp})
|
||||
pipe.zadd(keys["paths"], {_hash_member(path): timestamp})
|
||||
pipe.zadd(
|
||||
keys["statuses"], {f"{status_code}:{request_id}": timestamp}
|
||||
)
|
||||
pipe.zadd(keys["uas"], {_hash_member(user_agent): timestamp})
|
||||
pipe.zadd(
|
||||
keys["sizes"], {f"{response_size}:{request_id}": timestamp}
|
||||
)
|
||||
pipe.zadd(keys["methods"], {f"{method}:{request_id}": timestamp})
|
||||
pipe.zadd(
|
||||
keys["depths"], {f"{path_depth}:{request_id}": timestamp}
|
||||
)
|
||||
|
||||
for key in keys.values():
|
||||
pipe.zremrangebyscore(key, "-inf", trim_boundary)
|
||||
|
||||
pipe.zcount(keys["requests"], w1m, "+inf")
|
||||
pipe.zcount(keys["requests"], w5m, "+inf")
|
||||
pipe.zcount(keys["requests"], w10m, "+inf")
|
||||
pipe.zcount(keys["paths"], w5m, "+inf")
|
||||
pipe.zcount(keys["uas"], w10m, "+inf")
|
||||
pipe.zrangebyscore(keys["statuses"], w5m, "+inf")
|
||||
pipe.zrangebyscore(keys["sizes"], w5m, "+inf")
|
||||
pipe.zrangebyscore(keys["methods"], w5m, "+inf")
|
||||
pipe.zrangebyscore(keys["depths"], w5m, "+inf")
|
||||
pipe.zrangebyscore(
|
||||
keys["requests"], w10m, "+inf", withscores=True
|
||||
)
|
||||
|
||||
for key in keys.values():
|
||||
pipe.expire(key, KEY_TTL)
|
||||
|
||||
results = await pipe.execute()
|
||||
|
||||
read_start = 14
|
||||
req_count_1m = results[read_start]
|
||||
req_count_5m = results[read_start + 1]
|
||||
req_count_10m = results[read_start + 2]
|
||||
unique_paths_5m = results[read_start + 3]
|
||||
unique_uas_10m = results[read_start + 4]
|
||||
statuses_5m = results[read_start + 5]
|
||||
sizes_5m = results[read_start + 6]
|
||||
methods_5m = results[read_start + 7]
|
||||
depths_5m = results[read_start + 8]
|
||||
requests_with_scores = results[read_start + 9]
|
||||
|
||||
irt_mean, irt_std = _inter_request_time_stats(requests_with_scores)
|
||||
|
||||
return {
|
||||
"req_count_1m": float(req_count_1m),
|
||||
"req_count_5m": float(req_count_5m),
|
||||
"req_count_10m": float(req_count_10m),
|
||||
"error_rate_5m": _error_rate(statuses_5m),
|
||||
"unique_paths_5m": float(unique_paths_5m),
|
||||
"unique_uas_10m": float(unique_uas_10m),
|
||||
"method_entropy_5m": _method_entropy(methods_5m),
|
||||
"avg_response_size_5m": _avg_response_size(sizes_5m),
|
||||
"status_diversity_5m": _status_diversity(statuses_5m),
|
||||
"path_depth_variance_5m": _path_depth_variance(depths_5m),
|
||||
"inter_request_time_mean": irt_mean,
|
||||
"inter_request_time_std": irt_std,
|
||||
}
|
||||
|
||||
|
||||
def _error_rate(status_members: list[str]) -> float:
|
||||
"""
|
||||
Ratio of 4xx/5xx responses to total responses.
|
||||
"""
|
||||
if not status_members:
|
||||
return 0.0
|
||||
errors = sum(
|
||||
1 for m in status_members if int(m.split(":")[0]) >= 400
|
||||
)
|
||||
return errors / len(status_members)
|
||||
|
||||
|
||||
def _avg_response_size(size_members: list[str]) -> float:
|
||||
"""
|
||||
Mean response body size from size:request_id members.
|
||||
"""
|
||||
if not size_members:
|
||||
return 0.0
|
||||
sizes = [int(m.split(":")[0]) for m in size_members]
|
||||
return sum(sizes) / len(sizes)
|
||||
|
||||
|
||||
def _method_entropy(method_members: list[str]) -> float:
|
||||
"""
|
||||
Shannon entropy of HTTP method distribution.
|
||||
"""
|
||||
if not method_members:
|
||||
return 0.0
|
||||
methods = [m.split(":")[0] for m in method_members]
|
||||
counts = Counter(methods)
|
||||
total = len(methods)
|
||||
return -sum(
|
||||
(c / total) * math.log2(c / total) for c in counts.values()
|
||||
)
|
||||
|
||||
|
||||
def _status_diversity(status_members: list[str]) -> float:
|
||||
"""
|
||||
Count of distinct HTTP status codes.
|
||||
"""
|
||||
if not status_members:
|
||||
return 0.0
|
||||
codes = {m.split(":")[0] for m in status_members}
|
||||
return float(len(codes))
|
||||
|
||||
|
||||
def _path_depth_variance(depth_members: list[str]) -> float:
|
||||
"""
|
||||
Population variance of path depth values.
|
||||
"""
|
||||
if len(depth_members) < 2:
|
||||
return 0.0
|
||||
depths = [int(m.split(":")[0]) for m in depth_members]
|
||||
mean = sum(depths) / len(depths)
|
||||
return sum((d - mean) ** 2 for d in depths) / len(depths)
|
||||
|
||||
|
||||
def _inter_request_time_stats(
|
||||
entries: list[tuple[str, float]],
|
||||
) -> tuple[float, float]:
|
||||
"""
|
||||
Mean and standard deviation of inter-request intervals in milliseconds.
|
||||
"""
|
||||
if len(entries) < 2:
|
||||
return 0.0, 0.0
|
||||
timestamps = sorted(score for _, score in entries)
|
||||
deltas = [
|
||||
(timestamps[i + 1] - timestamps[i]) * 1000
|
||||
for i in range(len(timestamps) - 1)
|
||||
]
|
||||
mean = sum(deltas) / len(deltas)
|
||||
if len(deltas) < 2:
|
||||
return mean, 0.0
|
||||
variance = sum((d - mean) ** 2 for d in deltas) / len(deltas)
|
||||
return mean, math.sqrt(variance)
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
encoder.py
|
||||
"""
|
||||
|
||||
from app.core.features.mappings import (
|
||||
BOOLEAN_FEATURES,
|
||||
CATEGORICAL_ENCODERS,
|
||||
FEATURE_ORDER,
|
||||
)
|
||||
|
||||
|
||||
def _encode_country(code: str) -> float:
|
||||
"""
|
||||
Deterministic ordinal encoding for 2-letter ISO country codes.
|
||||
"""
|
||||
if not code or len(code) != 2:
|
||||
return 0.0
|
||||
return float((ord(code[0]) - 64) * 26 + (ord(code[1]) - 64))
|
||||
|
||||
|
||||
def encode_for_inference(
|
||||
features: dict[str, int | float | bool | str],
|
||||
) -> list[float]:
|
||||
"""
|
||||
Encode a combined feature dict into a 35-element float vector
|
||||
matching the model input specification.
|
||||
"""
|
||||
vector: list[float] = []
|
||||
|
||||
for name in FEATURE_ORDER:
|
||||
raw = features[name]
|
||||
|
||||
if name in BOOLEAN_FEATURES:
|
||||
vector.append(1.0 if raw else 0.0)
|
||||
elif name in CATEGORICAL_ENCODERS:
|
||||
vector.append(float(CATEGORICAL_ENCODERS[name].get(raw, 0)))
|
||||
elif name == "country_code":
|
||||
vector.append(_encode_country(raw))
|
||||
else:
|
||||
vector.append(float(raw))
|
||||
|
||||
return vector
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
extractor.py
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import math
|
||||
from collections import Counter
|
||||
from posixpath import splitext
|
||||
|
||||
from app.core.features.patterns import (
|
||||
ATTACK_COMBINED,
|
||||
DOUBLE_ENCODED,
|
||||
ENCODED_CHARS,
|
||||
)
|
||||
from app.core.features.signatures import BOT_USER_AGENTS, SCANNER_USER_AGENTS
|
||||
from app.core.ingestion.parsers import ParsedLogEntry
|
||||
|
||||
|
||||
def _shannon_entropy(s: str) -> float:
|
||||
"""
|
||||
Compute Shannon entropy of a string.
|
||||
"""
|
||||
if not s:
|
||||
return 0.0
|
||||
length = len(s)
|
||||
counts = Counter(s)
|
||||
return -sum(
|
||||
(c / length) * math.log2(c / length) for c in counts.values()
|
||||
)
|
||||
|
||||
|
||||
def _is_private_ip(ip_str: str) -> bool:
|
||||
"""
|
||||
Check whether an IP address is in a private or loopback range.
|
||||
"""
|
||||
try:
|
||||
return ipaddress.ip_address(ip_str).is_private
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def extract_request_features(
|
||||
entry: ParsedLogEntry,
|
||||
country_code: str = "",
|
||||
) -> dict[str, int | float | bool | str]:
|
||||
"""
|
||||
Extract 23 stateless per-request features from a parsed log entry.
|
||||
"""
|
||||
full_uri = entry.path
|
||||
if entry.query_string:
|
||||
full_uri = f"{entry.path}?{entry.query_string}"
|
||||
|
||||
ua_lower = entry.user_agent.lower()
|
||||
non_alnum = sum(1 for c in entry.path if not c.isalnum())
|
||||
path_len = len(entry.path)
|
||||
|
||||
_, ext = splitext(entry.path)
|
||||
|
||||
return {
|
||||
"http_method": entry.method,
|
||||
"path_depth": len([s for s in entry.path.split("/") if s]),
|
||||
"path_entropy": _shannon_entropy(entry.path),
|
||||
"path_length": path_len,
|
||||
"query_string_length": len(entry.query_string),
|
||||
"query_param_count": (
|
||||
len(entry.query_string.split("&")) if entry.query_string else 0
|
||||
),
|
||||
"has_encoded_chars": bool(ENCODED_CHARS.search(full_uri)),
|
||||
"has_double_encoding": bool(DOUBLE_ENCODED.search(full_uri)),
|
||||
"status_code": entry.status_code,
|
||||
"status_class": f"{entry.status_code // 100}xx",
|
||||
"response_size": entry.response_size,
|
||||
"hour_of_day": entry.timestamp.hour,
|
||||
"day_of_week": entry.timestamp.weekday(),
|
||||
"is_weekend": entry.timestamp.weekday() >= 5,
|
||||
"ua_length": len(entry.user_agent),
|
||||
"ua_entropy": _shannon_entropy(entry.user_agent),
|
||||
"is_known_bot": any(sig in ua_lower for sig in BOT_USER_AGENTS),
|
||||
"is_known_scanner": any(
|
||||
sig in ua_lower for sig in SCANNER_USER_AGENTS
|
||||
),
|
||||
"has_attack_pattern": bool(ATTACK_COMBINED.search(full_uri)),
|
||||
"special_char_ratio": non_alnum / path_len if path_len else 0.0,
|
||||
"file_extension": ext,
|
||||
"country_code": country_code,
|
||||
"is_private_ip": _is_private_ip(entry.ip),
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
mappings.py
|
||||
"""
|
||||
|
||||
METHOD_MAP: dict[str, int] = {
|
||||
"GET": 1,
|
||||
"POST": 2,
|
||||
"PUT": 3,
|
||||
"DELETE": 4,
|
||||
"PATCH": 5,
|
||||
"HEAD": 6,
|
||||
"OPTIONS": 7,
|
||||
}
|
||||
|
||||
STATUS_CLASS_MAP: dict[str, int] = {
|
||||
"1xx": 1,
|
||||
"2xx": 2,
|
||||
"3xx": 3,
|
||||
"4xx": 4,
|
||||
"5xx": 5,
|
||||
}
|
||||
|
||||
EXTENSION_MAP: dict[str, int] = {
|
||||
".html": 1,
|
||||
".htm": 2,
|
||||
".php": 3,
|
||||
".js": 4,
|
||||
".css": 5,
|
||||
".json": 6,
|
||||
".xml": 7,
|
||||
".jpg": 8,
|
||||
".jpeg": 9,
|
||||
".png": 10,
|
||||
".gif": 11,
|
||||
".svg": 12,
|
||||
".ico": 13,
|
||||
".pdf": 14,
|
||||
".zip": 15,
|
||||
".txt": 16,
|
||||
".asp": 17,
|
||||
".aspx": 18,
|
||||
".jsp": 19,
|
||||
".py": 20,
|
||||
".rb": 21,
|
||||
".woff2": 22,
|
||||
".woff": 23,
|
||||
".ttf": 24,
|
||||
".map": 25,
|
||||
}
|
||||
|
||||
FEATURE_ORDER: list[str] = [
|
||||
"http_method",
|
||||
"path_depth",
|
||||
"path_entropy",
|
||||
"path_length",
|
||||
"query_string_length",
|
||||
"query_param_count",
|
||||
"has_encoded_chars",
|
||||
"has_double_encoding",
|
||||
"status_code",
|
||||
"status_class",
|
||||
"response_size",
|
||||
"hour_of_day",
|
||||
"day_of_week",
|
||||
"is_weekend",
|
||||
"ua_length",
|
||||
"ua_entropy",
|
||||
"is_known_bot",
|
||||
"is_known_scanner",
|
||||
"has_attack_pattern",
|
||||
"special_char_ratio",
|
||||
"file_extension",
|
||||
"country_code",
|
||||
"is_private_ip",
|
||||
"req_count_1m",
|
||||
"req_count_5m",
|
||||
"req_count_10m",
|
||||
"error_rate_5m",
|
||||
"unique_paths_5m",
|
||||
"unique_uas_10m",
|
||||
"method_entropy_5m",
|
||||
"avg_response_size_5m",
|
||||
"status_diversity_5m",
|
||||
"path_depth_variance_5m",
|
||||
"inter_request_time_mean",
|
||||
"inter_request_time_std",
|
||||
]
|
||||
|
||||
CATEGORICAL_ENCODERS: dict[str, dict[str, int]] = {
|
||||
"http_method": METHOD_MAP,
|
||||
"status_class": STATUS_CLASS_MAP,
|
||||
"file_extension": EXTENSION_MAP,
|
||||
}
|
||||
|
||||
BOOLEAN_FEATURES: frozenset[str] = frozenset({
|
||||
"has_encoded_chars",
|
||||
"has_double_encoding",
|
||||
"is_weekend",
|
||||
"is_known_bot",
|
||||
"is_known_scanner",
|
||||
"has_attack_pattern",
|
||||
"is_private_ip",
|
||||
})
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
patterns.py
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
ENCODED_CHARS = re.compile(r"%[0-9a-fA-F]{2}")
|
||||
DOUBLE_ENCODED = re.compile(r"%25[0-9a-fA-F]{2}")
|
||||
|
||||
_SQLI = (
|
||||
r"(?:union\s+(?:all\s+)?select|"
|
||||
r"'\s*or\s+.+=|"
|
||||
r"'\s*and\s+.+=|"
|
||||
r"1\s*=\s*1|"
|
||||
r"sleep\s*\(|"
|
||||
r"benchmark\s*\(|"
|
||||
r"waitfor\s+delay|"
|
||||
r"extractvalue\s*\(|"
|
||||
r"updatexml\s*\(|"
|
||||
r"load_file\s*\(|"
|
||||
r"into\s+(?:out|dump)file|"
|
||||
r"group\s+by\s+.+having|"
|
||||
r"order\s+by\s+\d+|"
|
||||
r"(?:drop|alter|create)\s+table|"
|
||||
r"information_schema|"
|
||||
r"(?:char|concat|hex|unhex)\s*\(|"
|
||||
r"0x[0-9a-f]{6,}|"
|
||||
r"--\s*$|"
|
||||
r"/\*.*?\*/)"
|
||||
)
|
||||
|
||||
_XSS = (
|
||||
r"(?:<\s*script|"
|
||||
r"javascript\s*:|"
|
||||
r"vbscript\s*:|"
|
||||
r"on(?:error|load|click|mouse\w+|focus|blur|submit|change)\s*=|"
|
||||
r"<\s*(?:img|svg|iframe|object|embed|link|style|body|input|form)\b[^>]*\bon\w+\s*=|"
|
||||
r"<\s*iframe|"
|
||||
r"<\s*svg\b.*?on\w+\s*=|"
|
||||
r"document\s*\.\s*(?:cookie|write|location)|"
|
||||
r"window\s*\.\s*(?:location|open)|"
|
||||
r"eval\s*\(|"
|
||||
r"alert\s*\(|"
|
||||
r"prompt\s*\(|"
|
||||
r"confirm\s*\(|"
|
||||
r"expression\s*\(|"
|
||||
r"String\s*\.\s*fromCharCode)"
|
||||
)
|
||||
|
||||
_PATH_TRAVERSAL = (
|
||||
r"(?:\.\./|"
|
||||
r"\.\.\\|"
|
||||
r"%2e%2e[%/\\]|"
|
||||
r"%252e%252e|"
|
||||
r"(?:etc/(?:passwd|shadow|hosts)|"
|
||||
r"proc/self/|"
|
||||
r"windows/system32|"
|
||||
r"boot\.ini|"
|
||||
r"web\.config|"
|
||||
r"\.env|"
|
||||
r"\.git/config|"
|
||||
r"wp-config\.php))"
|
||||
)
|
||||
|
||||
_COMMAND_INJECTION = (
|
||||
r"(?:;\s*(?:ls|cat|rm|wget|curl|chmod|chown|nc|bash|sh|python|perl|ruby|php)\b|"
|
||||
r"\|\s*(?:cat|ls|id|whoami|uname|pwd|env|set|netstat|ifconfig|ip)\b|"
|
||||
r"\$\(|"
|
||||
r"`[^`]+`|"
|
||||
r"\$\{|"
|
||||
r">\s*/(?:etc|tmp|var)|"
|
||||
r"&&\s*(?:cat|ls|id|whoami|wget|curl)\b)"
|
||||
)
|
||||
|
||||
_FILE_INCLUSION = (
|
||||
r"(?:php://|"
|
||||
r"file://|"
|
||||
r"data://|"
|
||||
r"expect://|"
|
||||
r"input://|"
|
||||
r"zip://|"
|
||||
r"phar://|"
|
||||
r"glob://)"
|
||||
)
|
||||
|
||||
SQLI = re.compile(_SQLI, re.IGNORECASE)
|
||||
XSS = re.compile(_XSS, re.IGNORECASE)
|
||||
PATH_TRAVERSAL = re.compile(_PATH_TRAVERSAL, re.IGNORECASE)
|
||||
COMMAND_INJECTION = re.compile(_COMMAND_INJECTION, re.IGNORECASE)
|
||||
FILE_INCLUSION = re.compile(_FILE_INCLUSION, re.IGNORECASE)
|
||||
|
||||
ATTACK_COMBINED = re.compile(
|
||||
r"|".join((_SQLI, _XSS, _PATH_TRAVERSAL, _COMMAND_INJECTION, _FILE_INCLUSION)),
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
signatures.py
|
||||
"""
|
||||
|
||||
BOT_USER_AGENTS: frozenset[str] = frozenset({
|
||||
"googlebot",
|
||||
"bingbot",
|
||||
"slurp",
|
||||
"duckduckbot",
|
||||
"baiduspider",
|
||||
"yandexbot",
|
||||
"sogou",
|
||||
"facebot",
|
||||
"ia_archiver",
|
||||
"applebot",
|
||||
"petalbot",
|
||||
"semrushbot",
|
||||
"ahrefsbot",
|
||||
"mj12bot",
|
||||
"dotbot",
|
||||
"rogerbot",
|
||||
"linkedinbot",
|
||||
"twitterbot",
|
||||
"gptbot",
|
||||
"claudebot",
|
||||
"amazonbot",
|
||||
"bytespider",
|
||||
"ccbot",
|
||||
"dataforseo",
|
||||
"seznambot",
|
||||
"megaindex",
|
||||
"blexbot",
|
||||
"exabot",
|
||||
"archive.org_bot",
|
||||
"mojeekbot",
|
||||
"uptimerobot",
|
||||
"deadlinkchecker",
|
||||
"sitebulb",
|
||||
"screaming frog",
|
||||
})
|
||||
|
||||
SCANNER_USER_AGENTS: frozenset[str] = frozenset({
|
||||
"nikto",
|
||||
"sqlmap",
|
||||
"nessus",
|
||||
"openvas",
|
||||
"acunetix",
|
||||
"w3af",
|
||||
"nmap",
|
||||
"masscan",
|
||||
"zgrab",
|
||||
"gobuster",
|
||||
"dirbuster",
|
||||
"dirb",
|
||||
"wfuzz",
|
||||
"ffuf",
|
||||
"nuclei",
|
||||
"burp",
|
||||
"zap",
|
||||
"arachni",
|
||||
"skipfish",
|
||||
"wpscan",
|
||||
"joomscan",
|
||||
"whatweb",
|
||||
"httprint",
|
||||
"fierce",
|
||||
"subfinder",
|
||||
"amass",
|
||||
"httpx",
|
||||
"jaeles",
|
||||
"xray",
|
||||
"gau",
|
||||
"hakrawler",
|
||||
"katana",
|
||||
"cariddi",
|
||||
"gospider",
|
||||
"feroxbuster",
|
||||
"rustbuster",
|
||||
"patator",
|
||||
"hydra",
|
||||
"medusa",
|
||||
"metasploit",
|
||||
"cobalt",
|
||||
})
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
parsers.py
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ParsedLogEntry:
|
||||
"""
|
||||
Structured representation of a single nginx access log line.
|
||||
"""
|
||||
|
||||
ip: str
|
||||
timestamp: datetime
|
||||
method: str
|
||||
path: str
|
||||
query_string: str
|
||||
status_code: int
|
||||
response_size: int
|
||||
referer: str
|
||||
user_agent: str
|
||||
raw_line: str
|
||||
|
||||
|
||||
_TIMESTAMP_FMT = "%d/%b/%Y:%H:%M:%S %z"
|
||||
|
||||
_COMBINED_RE = re.compile(
|
||||
r"(?P<ip>\S+) \S+ \S+ "
|
||||
r"\[(?P<timestamp>[^\]]+)\] "
|
||||
r'"(?P<request>[^"]*)" '
|
||||
r"(?P<status>\d{3}) "
|
||||
r"(?P<size>\S+) "
|
||||
r'"(?P<referer>[^"]*)" '
|
||||
r'"(?P<user_agent>[^"]*)"'
|
||||
)
|
||||
|
||||
|
||||
def parse_combined(line: str) -> ParsedLogEntry | None:
|
||||
"""
|
||||
Parse an nginx combined-format log line using string-split primary
|
||||
with compiled regex fallback.
|
||||
"""
|
||||
if not line:
|
||||
return None
|
||||
|
||||
result = _parse_split(line)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
return _parse_regex(line)
|
||||
|
||||
|
||||
def _parse_split(line: str) -> ParsedLogEntry | None:
|
||||
"""
|
||||
Fast string-split parser for well-formed nginx combined lines.
|
||||
"""
|
||||
try:
|
||||
parts = line.split('"')
|
||||
if len(parts) < 6:
|
||||
return None
|
||||
|
||||
prefix = parts[0]
|
||||
request_line = parts[1]
|
||||
status_size = parts[2]
|
||||
referer_raw = parts[3]
|
||||
user_agent = parts[5]
|
||||
|
||||
bracket_open = prefix.index("[")
|
||||
bracket_close = prefix.index("]")
|
||||
ip = prefix[:bracket_open].split()[0]
|
||||
timestamp = datetime.strptime(
|
||||
prefix[bracket_open + 1 : bracket_close], _TIMESTAMP_FMT
|
||||
)
|
||||
|
||||
request_parts = request_line.split(" ", 2)
|
||||
method = request_parts[0]
|
||||
full_uri = request_parts[1] if len(request_parts) > 1 else ""
|
||||
|
||||
if "?" in full_uri:
|
||||
path, query_string = full_uri.split("?", 1)
|
||||
else:
|
||||
path = full_uri
|
||||
query_string = ""
|
||||
|
||||
tokens = status_size.strip().split()
|
||||
status_code = int(tokens[0])
|
||||
response_size = int(tokens[1]) if tokens[1] != "-" else 0
|
||||
|
||||
referer = "" if referer_raw == "-" else referer_raw
|
||||
|
||||
return ParsedLogEntry(
|
||||
ip=ip,
|
||||
timestamp=timestamp,
|
||||
method=method,
|
||||
path=path,
|
||||
query_string=query_string,
|
||||
status_code=status_code,
|
||||
response_size=response_size,
|
||||
referer=referer,
|
||||
user_agent=user_agent,
|
||||
raw_line=line,
|
||||
)
|
||||
except (ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def _parse_regex(line: str) -> ParsedLogEntry | None:
|
||||
"""
|
||||
Regex fallback for non-standard or edge-case log lines.
|
||||
"""
|
||||
match = _COMBINED_RE.match(line)
|
||||
if not match:
|
||||
return None
|
||||
|
||||
try:
|
||||
timestamp = datetime.strptime(match["timestamp"], _TIMESTAMP_FMT)
|
||||
|
||||
request_line = match["request"]
|
||||
request_parts = request_line.split(" ", 2)
|
||||
method = request_parts[0]
|
||||
full_uri = request_parts[1] if len(request_parts) > 1 else ""
|
||||
|
||||
if "?" in full_uri:
|
||||
path, query_string = full_uri.split("?", 1)
|
||||
else:
|
||||
path = full_uri
|
||||
query_string = ""
|
||||
|
||||
size_raw = match["size"]
|
||||
response_size = int(size_raw) if size_raw != "-" else 0
|
||||
|
||||
referer_raw = match["referer"]
|
||||
referer = "" if referer_raw == "-" else referer_raw
|
||||
|
||||
return ParsedLogEntry(
|
||||
ip=match["ip"],
|
||||
timestamp=timestamp,
|
||||
method=method,
|
||||
path=path,
|
||||
query_string=query_string,
|
||||
status_code=int(match["status"]),
|
||||
response_size=response_size,
|
||||
referer=referer,
|
||||
user_agent=match["user_agent"],
|
||||
raw_line=line,
|
||||
)
|
||||
except (ValueError, IndexError):
|
||||
return None
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
pipeline.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import uuid
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
|
||||
from app.core.detection.rules import RuleEngine, RuleResult
|
||||
from app.core.enrichment.geoip import GeoIPService, GeoResult
|
||||
from app.core.features.aggregator import WindowAggregator
|
||||
from app.core.features.encoder import encode_for_inference
|
||||
from app.core.features.extractor import extract_request_features
|
||||
from app.core.ingestion.parsers import ParsedLogEntry, parse_combined
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class EnrichedRequest:
|
||||
"""
|
||||
A parsed log entry enriched with extracted features and GeoIP data.
|
||||
"""
|
||||
entry: ParsedLogEntry
|
||||
features: dict[str, int | float | bool | str]
|
||||
feature_vector: list[float]
|
||||
geo: GeoResult | None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ScoredRequest:
|
||||
"""
|
||||
A fully scored request ready for dispatch.
|
||||
"""
|
||||
entry: ParsedLogEntry
|
||||
features: dict[str, int | float | bool | str]
|
||||
feature_vector: list[float]
|
||||
geo: GeoResult | None
|
||||
rule_result: RuleResult
|
||||
|
||||
|
||||
class Pipeline:
|
||||
"""
|
||||
Four-stage async pipeline that transforms raw log lines
|
||||
into scored threat candidates.
|
||||
|
||||
Stages:
|
||||
raw_queue → [parse] → parsed_queue → [enrich+features]
|
||||
→ feature_queue → [detect] → alert_queue → [dispatch]
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
redis_client: aioredis.Redis,
|
||||
rule_engine: RuleEngine,
|
||||
geoip: GeoIPService | None = None,
|
||||
on_result: Callable[[ScoredRequest], Awaitable[None]] | None = None,
|
||||
raw_queue_size: int = 1000,
|
||||
parsed_queue_size: int = 500,
|
||||
feature_queue_size: int = 200,
|
||||
alert_queue_size: int = 100,
|
||||
) -> None:
|
||||
self.raw_queue: asyncio.Queue[str | None] = asyncio.Queue(
|
||||
maxsize=raw_queue_size,
|
||||
)
|
||||
self._parsed_queue: asyncio.Queue[ParsedLogEntry | None] = asyncio.Queue(
|
||||
maxsize=parsed_queue_size,
|
||||
)
|
||||
self._feature_queue: asyncio.Queue[EnrichedRequest | None] = asyncio.Queue(
|
||||
maxsize=feature_queue_size,
|
||||
)
|
||||
self._alert_queue: asyncio.Queue[ScoredRequest | None] = asyncio.Queue(
|
||||
maxsize=alert_queue_size,
|
||||
)
|
||||
|
||||
self._aggregator = WindowAggregator(redis_client)
|
||||
self._rule_engine = rule_engine
|
||||
self._geoip = geoip
|
||||
self._on_result = on_result
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
|
||||
async def start(self) -> None:
|
||||
"""
|
||||
Spawn worker tasks for each pipeline stage.
|
||||
"""
|
||||
self._tasks = [
|
||||
asyncio.create_task(self._parse_worker(), name="parse"),
|
||||
asyncio.create_task(self._feature_worker(), name="feature"),
|
||||
asyncio.create_task(self._detection_worker(), name="detection"),
|
||||
asyncio.create_task(self._dispatch_worker(), name="dispatch"),
|
||||
]
|
||||
logger.info("Pipeline started — 4 stage workers running")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""
|
||||
Send a poison pill through the chain and wait for all workers to exit.
|
||||
"""
|
||||
await self.raw_queue.put(None)
|
||||
await asyncio.gather(*self._tasks)
|
||||
logger.info("Pipeline stopped — all workers exited")
|
||||
|
||||
async def _parse_worker(self) -> None:
|
||||
"""
|
||||
Stage 1: Parse raw log lines into structured entries.
|
||||
"""
|
||||
while True:
|
||||
line = await self.raw_queue.get()
|
||||
if line is None:
|
||||
self.raw_queue.task_done()
|
||||
await self._parsed_queue.put(None)
|
||||
break
|
||||
try:
|
||||
entry = parse_combined(line)
|
||||
if entry is not None:
|
||||
await self._parsed_queue.put(entry)
|
||||
except Exception:
|
||||
logger.exception("Parse error")
|
||||
self.raw_queue.task_done()
|
||||
|
||||
async def _feature_worker(self) -> None:
|
||||
"""
|
||||
Stage 2: Enrich with GeoIP, extract per-request features,
|
||||
aggregate per-IP windowed features, and encode the 35-dim vector.
|
||||
"""
|
||||
while True:
|
||||
entry = await self._parsed_queue.get()
|
||||
if entry is None:
|
||||
self._parsed_queue.task_done()
|
||||
await self._feature_queue.put(None)
|
||||
break
|
||||
try:
|
||||
country_code = ""
|
||||
geo = None
|
||||
if self._geoip is not None:
|
||||
geo = await self._geoip.lookup(entry.ip)
|
||||
if geo and geo.country:
|
||||
country_code = geo.country
|
||||
|
||||
per_request = extract_request_features(entry, country_code)
|
||||
|
||||
windowed = await self._aggregator.record_and_aggregate(
|
||||
ip=entry.ip,
|
||||
request_id=uuid.uuid4().hex,
|
||||
path=entry.path,
|
||||
path_depth=per_request["path_depth"],
|
||||
method=entry.method,
|
||||
status_code=entry.status_code,
|
||||
user_agent=entry.user_agent,
|
||||
response_size=entry.response_size,
|
||||
timestamp=entry.timestamp.timestamp(),
|
||||
)
|
||||
|
||||
merged = {**per_request, **windowed}
|
||||
vector = encode_for_inference(merged)
|
||||
|
||||
await self._feature_queue.put(
|
||||
EnrichedRequest(
|
||||
entry=entry,
|
||||
features=merged,
|
||||
feature_vector=vector,
|
||||
geo=geo,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Feature extraction failed for %s", entry.ip)
|
||||
self._parsed_queue.task_done()
|
||||
|
||||
async def _detection_worker(self) -> None:
|
||||
"""
|
||||
Stage 3: Score enriched requests using the rule engine.
|
||||
"""
|
||||
while True:
|
||||
enriched = await self._feature_queue.get()
|
||||
if enriched is None:
|
||||
self._feature_queue.task_done()
|
||||
await self._alert_queue.put(None)
|
||||
break
|
||||
try:
|
||||
rule_result = self._rule_engine.score_request(
|
||||
enriched.features, enriched.entry,
|
||||
)
|
||||
await self._alert_queue.put(
|
||||
ScoredRequest(
|
||||
entry=enriched.entry,
|
||||
features=enriched.features,
|
||||
feature_vector=enriched.feature_vector,
|
||||
geo=enriched.geo,
|
||||
rule_result=rule_result,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Detection failed")
|
||||
self._feature_queue.task_done()
|
||||
|
||||
async def _dispatch_worker(self) -> None:
|
||||
"""
|
||||
Stage 4: Dispatch scored results via the on_result callback.
|
||||
"""
|
||||
while True:
|
||||
scored = await self._alert_queue.get()
|
||||
if scored is None:
|
||||
self._alert_queue.task_done()
|
||||
break
|
||||
try:
|
||||
if self._on_result is not None:
|
||||
await self._on_result(scored)
|
||||
except Exception:
|
||||
logger.exception("Dispatch failed for %s", scored.entry.ip)
|
||||
self._alert_queue.task_done()
|
||||
|
|
@ -0,0 +1,185 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
tailer.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from watchdog.events import (
|
||||
FileCreatedEvent,
|
||||
FileModifiedEvent,
|
||||
FileMovedEvent,
|
||||
FileSystemEventHandler,
|
||||
)
|
||||
from watchdog.observers import Observer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LogHandler(FileSystemEventHandler):
|
||||
"""
|
||||
Watchdog event handler that detects modifications and log rotation
|
||||
for a single target file, pushing new lines into an asyncio.Queue.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
target: str,
|
||||
queue: asyncio.Queue[str],
|
||||
loop: asyncio.AbstractEventLoop,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self._target = target
|
||||
self._queue = queue
|
||||
self._loop = loop
|
||||
self._file = None
|
||||
self._inode: int | None = None
|
||||
self._open_target()
|
||||
|
||||
def _open_target(self) -> None:
|
||||
"""
|
||||
Open the target log file and seek to the end.
|
||||
"""
|
||||
try:
|
||||
self._file = open(self._target, encoding="utf-8", errors="replace")
|
||||
self._file.seek(0, os.SEEK_END)
|
||||
self._inode = os.stat(self._target).st_ino
|
||||
logger.info("Tailing %s (inode %s)", self._target, self._inode)
|
||||
except FileNotFoundError:
|
||||
logger.warning("Log file %s not found — waiting for creation", self._target)
|
||||
self._file = None
|
||||
self._inode = None
|
||||
|
||||
def _read_new_lines(self) -> None:
|
||||
"""
|
||||
Read all new complete lines from the current file position.
|
||||
"""
|
||||
if self._file is None:
|
||||
return
|
||||
|
||||
for line in self._file:
|
||||
stripped = line.rstrip("\n\r")
|
||||
if stripped:
|
||||
self._loop.call_soon_threadsafe(self._queue.put_nowait, stripped)
|
||||
|
||||
def _handle_rotation(self) -> None:
|
||||
"""
|
||||
Finish reading the old file, then reopen the target at position 0.
|
||||
"""
|
||||
self._read_new_lines()
|
||||
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
|
||||
try:
|
||||
self._file = open(self._target, encoding="utf-8", errors="replace")
|
||||
self._inode = os.stat(self._target).st_ino
|
||||
logger.info("Rotated to new %s (inode %s)", self._target, self._inode)
|
||||
except FileNotFoundError:
|
||||
self._file = None
|
||||
self._inode = None
|
||||
|
||||
def _inode_changed(self) -> bool:
|
||||
"""
|
||||
Check whether the target file's inode differs from the one we opened.
|
||||
"""
|
||||
try:
|
||||
current_inode = os.stat(self._target).st_ino
|
||||
return current_inode != self._inode
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
def on_modified(self, event: FileModifiedEvent) -> None:
|
||||
"""
|
||||
Handle new data appended to the log file.
|
||||
"""
|
||||
if not isinstance(event, FileModifiedEvent) or event.is_directory:
|
||||
return
|
||||
|
||||
if Path(event.src_path).resolve() != Path(self._target).resolve():
|
||||
return
|
||||
|
||||
if self._inode_changed():
|
||||
self._handle_rotation()
|
||||
return
|
||||
|
||||
self._read_new_lines()
|
||||
|
||||
def on_moved(self, event: FileMovedEvent) -> None:
|
||||
"""
|
||||
Handle log rotation via rename (access.log -> access.log.1).
|
||||
"""
|
||||
if not isinstance(event, FileMovedEvent):
|
||||
return
|
||||
|
||||
if Path(event.src_path).resolve() == Path(self._target).resolve():
|
||||
logger.info("Log rotated: %s -> %s", event.src_path, event.dest_path)
|
||||
self._handle_rotation()
|
||||
|
||||
def on_created(self, event: FileCreatedEvent) -> None:
|
||||
"""
|
||||
Handle log rotation where a new file is created at the target path.
|
||||
"""
|
||||
if not isinstance(event, FileCreatedEvent) or event.is_directory:
|
||||
return
|
||||
|
||||
if Path(event.src_path).resolve() == Path(self._target).resolve():
|
||||
logger.info("New log file created: %s", event.src_path)
|
||||
self._handle_rotation()
|
||||
|
||||
def close(self) -> None:
|
||||
"""
|
||||
Close the underlying file handle.
|
||||
"""
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
|
||||
class LogTailer:
|
||||
"""
|
||||
Watchdog-based nginx log tailer that pushes raw lines
|
||||
into an asyncio.Queue for downstream processing.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
log_path: str,
|
||||
queue: asyncio.Queue[str],
|
||||
loop: asyncio.AbstractEventLoop,
|
||||
) -> None:
|
||||
self._log_path = log_path
|
||||
self._handler = _LogHandler(log_path, queue, loop)
|
||||
self._observer = Observer()
|
||||
self._started = False
|
||||
|
||||
def start(self) -> None:
|
||||
"""
|
||||
Begin watching the log file's parent directory for changes.
|
||||
"""
|
||||
watch_dir = str(Path(self._log_path).resolve().parent)
|
||||
self._observer.schedule(self._handler, watch_dir, recursive=False)
|
||||
self._observer.start()
|
||||
self._started = True
|
||||
logger.info("LogTailer started — watching %s", watch_dir)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""
|
||||
Stop the watchdog observer and close file handles.
|
||||
"""
|
||||
if self._started:
|
||||
self._observer.stop()
|
||||
self._observer.join(timeout=5)
|
||||
self._started = False
|
||||
self._handler.close()
|
||||
logger.info("LogTailer stopped")
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
"""
|
||||
Whether the tailer is currently running.
|
||||
"""
|
||||
return self._started and self._observer.is_alive()
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
redis_manager.py
|
||||
"""
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
class RedisManager:
|
||||
"""
|
||||
Async Redis connection lifecycle manager.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._client: aioredis.Redis | None = None
|
||||
|
||||
async def connect(self) -> None:
|
||||
"""
|
||||
Create the async Redis client from configured URL.
|
||||
"""
|
||||
self._client = aioredis.from_url(
|
||||
settings.redis_url,
|
||||
decode_responses=True,
|
||||
)
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""
|
||||
Close the Redis connection and release resources.
|
||||
"""
|
||||
if self._client:
|
||||
await self._client.aclose()
|
||||
self._client = None
|
||||
|
||||
@property
|
||||
def client(self) -> aioredis.Redis | None:
|
||||
"""
|
||||
Return the active Redis client or None if not connected.
|
||||
"""
|
||||
return self._client
|
||||
|
||||
async def ping(self) -> bool:
|
||||
"""
|
||||
Check Redis connectivity via PING command.
|
||||
"""
|
||||
if not self._client:
|
||||
return False
|
||||
try:
|
||||
return await self._client.ping()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
redis_manager = RedisManager()
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
factory.py
|
||||
"""
|
||||
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.config import settings
|
||||
from app.core.redis_manager import redis_manager
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
"""
|
||||
Manage application startup and shutdown lifecycle
|
||||
"""
|
||||
app.state.startup_time = time.monotonic()
|
||||
app.state.pipeline_running = False
|
||||
|
||||
await redis_manager.connect()
|
||||
|
||||
yield
|
||||
|
||||
await redis_manager.disconnect()
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
"""
|
||||
Build and configure the AngelusVigil FastAPI application
|
||||
"""
|
||||
app = FastAPI(
|
||||
title=settings.app_name,
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.state.startup_time = time.monotonic()
|
||||
app.state.pipeline_running = False
|
||||
|
||||
from app.api.health import router as health_router
|
||||
|
||||
app.include_router(health_router)
|
||||
|
||||
return app
|
||||
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
main.py
|
||||
"""
|
||||
|
||||
from app.factory import create_app
|
||||
|
||||
app = create_app()
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
||||
from app.models.model_metadata import ModelMetadata
|
||||
from app.models.threat_event import ThreatEvent
|
||||
|
||||
__all__ = ["ModelMetadata", "ThreatEvent"]
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
base.py
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, text
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
class TimestampedModel(SQLModel):
|
||||
"""
|
||||
Abstract base providing UUID primary key and timezone-aware created_at.
|
||||
"""
|
||||
|
||||
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
|
||||
created_at: datetime = Field(
|
||||
sa_type=DateTime(timezone=True),
|
||||
sa_column_kwargs={"server_default": text("CURRENT_TIMESTAMP")},
|
||||
nullable=False,
|
||||
)
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
model_metadata.py
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, Index, JSON, text
|
||||
from sqlmodel import Field
|
||||
|
||||
from app.models.base import TimestampedModel
|
||||
|
||||
|
||||
class ModelMetadata(TimestampedModel, table=True):
|
||||
"""
|
||||
Tracks ML model versions, training metrics, and deployment status.
|
||||
"""
|
||||
|
||||
__tablename__ = "model_metadata"
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"idx_model_metadata_active",
|
||||
"model_type",
|
||||
unique=True,
|
||||
postgresql_where=text("is_active = TRUE"),
|
||||
),
|
||||
)
|
||||
|
||||
model_type: str = Field(max_length=30)
|
||||
version: str = Field(max_length=64)
|
||||
training_samples: int
|
||||
metrics: dict = Field(sa_column=Column(JSON, nullable=False))
|
||||
artifact_path: str
|
||||
is_active: bool = Field(default=False)
|
||||
mlflow_run_id: str | None = Field(default=None, max_length=64)
|
||||
threshold: float | None = Field(default=None)
|
||||
notes: str | None = Field(default=None)
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
threat_event.py
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, Float, Index, JSON, SmallInteger, text
|
||||
from sqlmodel import Field
|
||||
|
||||
from app.models.base import TimestampedModel
|
||||
|
||||
|
||||
class ThreatEvent(TimestampedModel, table=True):
|
||||
"""
|
||||
Primary table for detected threat events.
|
||||
"""
|
||||
|
||||
__tablename__ = "threat_events"
|
||||
__table_args__ = (
|
||||
Index("idx_threat_events_created_at", "created_at"),
|
||||
Index("idx_threat_events_source_ip", "source_ip"),
|
||||
Index("idx_threat_events_severity", "severity"),
|
||||
Index("idx_threat_events_score", "threat_score"),
|
||||
Index(
|
||||
"idx_threat_events_reviewed",
|
||||
"reviewed",
|
||||
postgresql_where=text("reviewed = FALSE"),
|
||||
),
|
||||
)
|
||||
|
||||
source_ip: str = Field(max_length=45)
|
||||
request_method: str = Field(max_length=10)
|
||||
request_path: str
|
||||
status_code: int = Field(
|
||||
sa_column=Column(SmallInteger, nullable=False)
|
||||
)
|
||||
response_size: int
|
||||
user_agent: str
|
||||
threat_score: float = Field(
|
||||
sa_column=Column(Float, nullable=False)
|
||||
)
|
||||
severity: str = Field(max_length=6)
|
||||
component_scores: dict[str, float] = Field(
|
||||
sa_column=Column(JSON, nullable=False)
|
||||
)
|
||||
geo_country: str | None = Field(default=None, max_length=2)
|
||||
geo_city: str | None = Field(default=None, max_length=255)
|
||||
geo_lat: float | None = Field(default=None)
|
||||
geo_lon: float | None = Field(default=None)
|
||||
feature_vector: list[float] = Field(
|
||||
sa_column=Column(JSON, nullable=False)
|
||||
)
|
||||
matched_rules: list[str] | None = Field(
|
||||
default=None, sa_column=Column(JSON, nullable=True)
|
||||
)
|
||||
model_version: str | None = Field(default=None, max_length=64)
|
||||
reviewed: bool = Field(default=False)
|
||||
review_label: str | None = Field(default=None, max_length=20)
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,221 @@
|
|||
# ©AngelaMos | 2026
|
||||
# pyproject.toml
|
||||
|
||||
[project]
|
||||
name = "angelusvigil"
|
||||
version = "0.1.0"
|
||||
description = "AI-powered threat detection engine for web server access logs"
|
||||
requires-python = ">=3.14"
|
||||
authors = [
|
||||
{name = "Carter", email = "carter@certgames.com"}
|
||||
]
|
||||
|
||||
dependencies = [
|
||||
"fastapi>=0.128.8",
|
||||
"uvicorn[standard]>=0.40.0",
|
||||
"redis[hiredis]>=7.1.1",
|
||||
"sqlalchemy>=2.0.46",
|
||||
"sqlmodel>=0.0.33",
|
||||
"alembic>=1.18.4",
|
||||
"asyncpg>=0.31.0",
|
||||
"pydantic>=2.12.5",
|
||||
"pydantic-settings>=2.12.0",
|
||||
"watchdog>=6.0.0",
|
||||
"geoip2>=5.2.0",
|
||||
"typer>=0.23.0",
|
||||
"orjson>=3.11.7",
|
||||
"httpx>=0.28.1",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=9.0.2",
|
||||
"pytest-asyncio>=1.3.0",
|
||||
"aiosqlite>=0.22.1",
|
||||
"ruff>=0.15.0",
|
||||
"mypy>=1.19.1",
|
||||
"pylint>=4.0.4",
|
||||
"pylint-pydantic>=0.4.1",
|
||||
"types-redis>=4.6.0.20241004",
|
||||
"coverage>=7.13.4",
|
||||
"fakeredis>=2.26.0",
|
||||
]
|
||||
|
||||
ml = [
|
||||
"torch>=2.10.0",
|
||||
"scikit-learn>=1.8.0",
|
||||
"onnxruntime>=1.24.1",
|
||||
"skl2onnx>=1.20.0",
|
||||
"mlflow>=3.9.0",
|
||||
"numpy>=2.4.2",
|
||||
"pandas>=2.2.0,<3",
|
||||
"imbalanced-learn>=0.14.1",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
vigil = "cli.main:app"
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["app", "cli", "ml"]
|
||||
|
||||
[tool.ruff]
|
||||
target-version = "py314"
|
||||
line-length = 95
|
||||
indent-width = 4
|
||||
exclude = [
|
||||
".bzr",
|
||||
".direnv",
|
||||
".eggs",
|
||||
".git",
|
||||
".git-rewrite",
|
||||
".hg",
|
||||
".ipynb_checkpoints",
|
||||
".mypy_cache",
|
||||
".nox",
|
||||
".pyenv",
|
||||
".pytest_cache",
|
||||
".pytype",
|
||||
".ruff_cache",
|
||||
".svn",
|
||||
".tox",
|
||||
".venv",
|
||||
"__pycache__",
|
||||
"_build",
|
||||
"build",
|
||||
"dist",
|
||||
"site-packages",
|
||||
"venv",
|
||||
"alembic",
|
||||
]
|
||||
|
||||
[tool.ruff.format]
|
||||
line-ending = "auto"
|
||||
skip-magic-trailing-comma = false
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = [
|
||||
"E1",
|
||||
"E4",
|
||||
"E7",
|
||||
"F",
|
||||
"W292",
|
||||
"W605",
|
||||
"B",
|
||||
"C4",
|
||||
"UP",
|
||||
"ARG",
|
||||
"SIM",
|
||||
"I",
|
||||
"F401",
|
||||
"F811",
|
||||
"F821",
|
||||
]
|
||||
|
||||
ignore = [
|
||||
"E501",
|
||||
"W291",
|
||||
"W293",
|
||||
"I001",
|
||||
"RUF001",
|
||||
"RUF002",
|
||||
"B008",
|
||||
"ARG001",
|
||||
"E712",
|
||||
]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"__init__.py" = ["F401"]
|
||||
"tests/*" = ["ARG002"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.14"
|
||||
strict = true
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = true
|
||||
disallow_any_generics = true
|
||||
check_untyped_defs = true
|
||||
no_implicit_optional = true
|
||||
warn_redundant_casts = true
|
||||
warn_unused_ignores = true
|
||||
warn_no_return = true
|
||||
follow_imports = "normal"
|
||||
ignore_missing_imports = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = "app.models.*"
|
||||
disable_error_code = ["call-arg", "misc"]
|
||||
|
||||
[tool.pylint.main]
|
||||
py-version = "3.12"
|
||||
jobs = 4
|
||||
load-plugins = [
|
||||
"pylint_pydantic",
|
||||
]
|
||||
persistent = true
|
||||
suggestion-mode = true
|
||||
ignore = [
|
||||
"venv",
|
||||
".venv",
|
||||
"__pycache__",
|
||||
"build",
|
||||
"dist",
|
||||
".git",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
".ruff_cache",
|
||||
"alembic",
|
||||
]
|
||||
ignore-paths = [
|
||||
"^venv/.*",
|
||||
"^.venv/.*",
|
||||
"^build/.*",
|
||||
"^dist/.*",
|
||||
]
|
||||
|
||||
[tool.pylint.messages_control]
|
||||
disable = [
|
||||
"C0111",
|
||||
"C0103",
|
||||
"R0903",
|
||||
"W0511",
|
||||
"W0622",
|
||||
"W0612",
|
||||
"W0613",
|
||||
"C0301",
|
||||
"C0302",
|
||||
"C0411",
|
||||
"C0305",
|
||||
"C0303",
|
||||
"C0304",
|
||||
"R0801",
|
||||
"E0401",
|
||||
"C0412",
|
||||
"W0718",
|
||||
"E0611",
|
||||
"E1101",
|
||||
]
|
||||
|
||||
[tool.pylint.design]
|
||||
max-args = 7
|
||||
max-attributes = 10
|
||||
max-locals = 30
|
||||
max-positional-arguments = 7
|
||||
|
||||
[tool.pylint."messages control"]
|
||||
per-file-ignores = [
|
||||
"alembic/env.py:W0611",
|
||||
"app/services/*:C0121",
|
||||
"tests/*:W0212,W0621",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_classes = ["Test*"]
|
||||
python_functions = ["test_*"]
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
__init__.py
|
||||
"""
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
conftest.py
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_settings() -> Settings:
|
||||
"""
|
||||
Override settings for test environment.
|
||||
"""
|
||||
return Settings(
|
||||
env="testing",
|
||||
debug=False,
|
||||
database_url="sqlite+aiosqlite:///test.db",
|
||||
redis_url="redis://localhost:6379/1",
|
||||
nginx_log_path="/tmp/test-access.log",
|
||||
geoip_db_path="/tmp/nonexistent.mmdb",
|
||||
)
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
test_api.py
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_health_returns_200() -> None:
|
||||
"""
|
||||
Health endpoint returns 200 with status and uptime.
|
||||
"""
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/health")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "healthy"
|
||||
assert "uptime_seconds" in data
|
||||
assert isinstance(data["uptime_seconds"], (int, float))
|
||||
assert "pipeline_running" in data
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_health_returns_pipeline_status() -> None:
|
||||
"""
|
||||
Health response includes pipeline_running boolean.
|
||||
"""
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/health")
|
||||
|
||||
data = response.json()
|
||||
assert isinstance(data["pipeline_running"], bool)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ready_returns_check_structure() -> None:
|
||||
"""
|
||||
Readiness endpoint returns structured component checks.
|
||||
"""
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/ready")
|
||||
|
||||
assert response.status_code in (200, 503)
|
||||
data = response.json()
|
||||
assert "status" in data
|
||||
assert "checks" in data
|
||||
assert "database" in data["checks"]
|
||||
assert "redis" in data["checks"]
|
||||
assert "models_loaded" in data["checks"]
|
||||
|
|
@ -0,0 +1,234 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
test_detection.py
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.core.detection.rules import RuleEngine, RuleResult
|
||||
from app.core.ingestion.parsers import ParsedLogEntry
|
||||
|
||||
|
||||
def _make_entry(
|
||||
path: str = "/api/v1/users",
|
||||
query_string: str = "",
|
||||
method: str = "GET",
|
||||
status_code: int = 200,
|
||||
user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
|
||||
) -> ParsedLogEntry:
|
||||
"""
|
||||
Build a ParsedLogEntry with sensible defaults for rule engine testing.
|
||||
"""
|
||||
return ParsedLogEntry(
|
||||
ip="93.184.216.34",
|
||||
timestamp=datetime(2026, 2, 11, 14, 30, 0, tzinfo=timezone.utc),
|
||||
method=method,
|
||||
path=path,
|
||||
query_string=query_string,
|
||||
status_code=status_code,
|
||||
response_size=1234,
|
||||
referer="",
|
||||
user_agent=user_agent,
|
||||
raw_line="",
|
||||
)
|
||||
|
||||
|
||||
def _empty_windowed() -> dict[str, float]:
|
||||
"""
|
||||
Windowed features representing a quiet IP.
|
||||
"""
|
||||
return {
|
||||
"req_count_1m": 1.0,
|
||||
"req_count_5m": 3.0,
|
||||
"req_count_10m": 5.0,
|
||||
"error_rate_5m": 0.0,
|
||||
"unique_paths_5m": 2.0,
|
||||
"unique_uas_10m": 1.0,
|
||||
"method_entropy_5m": 0.0,
|
||||
"avg_response_size_5m": 1024.0,
|
||||
"status_diversity_5m": 1.0,
|
||||
"path_depth_variance_5m": 0.0,
|
||||
"inter_request_time_mean": 5000.0,
|
||||
"inter_request_time_std": 1000.0,
|
||||
}
|
||||
|
||||
|
||||
ENGINE = RuleEngine()
|
||||
|
||||
|
||||
def test_normal_request_low_severity() -> None:
|
||||
"""
|
||||
A benign GET request scores below 0.5 with LOW severity.
|
||||
"""
|
||||
result = ENGINE.score_request(_empty_windowed(), _make_entry())
|
||||
assert result.threat_score < 0.5
|
||||
assert result.severity == "LOW"
|
||||
assert result.matched_rules == []
|
||||
|
||||
|
||||
def test_sqli_in_query_string() -> None:
|
||||
"""
|
||||
SQL injection payload triggers HIGH severity with SQL_INJECTION rule.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/users",
|
||||
query_string="id=1' UNION SELECT username,password FROM users--",
|
||||
)
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert result.threat_score >= 0.7
|
||||
assert result.severity == "HIGH"
|
||||
assert "SQL_INJECTION" in result.matched_rules
|
||||
|
||||
|
||||
def test_xss_in_query_string() -> None:
|
||||
"""
|
||||
XSS payload triggers HIGH severity with XSS rule.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/comment",
|
||||
query_string="body=<script>alert(document.cookie)</script>",
|
||||
)
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert result.threat_score >= 0.7
|
||||
assert result.severity == "HIGH"
|
||||
assert "XSS" in result.matched_rules
|
||||
|
||||
|
||||
def test_path_traversal() -> None:
|
||||
"""
|
||||
Path traversal triggers at least MEDIUM severity.
|
||||
"""
|
||||
entry = _make_entry(path="/static/../../etc/passwd")
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert result.threat_score >= 0.5
|
||||
assert result.severity in {"MEDIUM", "HIGH"}
|
||||
assert "PATH_TRAVERSAL" in result.matched_rules
|
||||
|
||||
|
||||
def test_command_injection() -> None:
|
||||
"""
|
||||
Command injection triggers HIGH severity.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/ping",
|
||||
query_string="host=127.0.0.1;cat /etc/passwd",
|
||||
)
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert result.threat_score >= 0.7
|
||||
assert result.severity == "HIGH"
|
||||
assert "COMMAND_INJECTION" in result.matched_rules
|
||||
|
||||
|
||||
def test_scanner_ua_contributes() -> None:
|
||||
"""
|
||||
Known scanner UA fires the SCANNER_UA rule.
|
||||
"""
|
||||
entry = _make_entry(user_agent="Mozilla/5.00 (Nikto/2.1.6)")
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert "SCANNER_UA" in result.matched_rules
|
||||
assert result.threat_score > 0.0
|
||||
|
||||
|
||||
def test_rate_anomaly() -> None:
|
||||
"""
|
||||
High request rate in the 1-minute window fires RATE_ANOMALY.
|
||||
"""
|
||||
windowed = _empty_windowed()
|
||||
windowed["req_count_1m"] = 150.0
|
||||
result = ENGINE.score_request(windowed, _make_entry())
|
||||
assert "RATE_ANOMALY" in result.matched_rules
|
||||
assert result.threat_score > 0.0
|
||||
|
||||
|
||||
def test_multiple_rules_aggregate() -> None:
|
||||
"""
|
||||
Multiple triggered rules produce a higher score than any single rule alone.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/users",
|
||||
query_string="id=1' OR 1=1--",
|
||||
user_agent="sqlmap/1.8",
|
||||
)
|
||||
sqli_only = ENGINE.score_request(
|
||||
_empty_windowed(),
|
||||
_make_entry(path="/users", query_string="id=1' OR 1=1--"),
|
||||
)
|
||||
combined = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert combined.threat_score > sqli_only.threat_score
|
||||
assert len(combined.matched_rules) > len(sqli_only.matched_rules)
|
||||
|
||||
|
||||
def test_score_clamped_to_unit_range() -> None:
|
||||
"""
|
||||
Score never exceeds 1.0 even with many triggered rules.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/static/../../etc/passwd;cat /etc/shadow",
|
||||
query_string="id=1' UNION SELECT 1--&x=<script>alert(1)</script>",
|
||||
user_agent="sqlmap/1.8",
|
||||
)
|
||||
windowed = _empty_windowed()
|
||||
windowed["req_count_1m"] = 200.0
|
||||
windowed["error_rate_5m"] = 0.8
|
||||
result = ENGINE.score_request(windowed, entry)
|
||||
assert 0.0 <= result.threat_score <= 1.0
|
||||
|
||||
|
||||
def test_severity_thresholds() -> None:
|
||||
"""
|
||||
Severity classification follows the architecture thresholds.
|
||||
"""
|
||||
low = ENGINE.score_request(_empty_windowed(), _make_entry())
|
||||
assert low.severity == "LOW"
|
||||
|
||||
medium = ENGINE.score_request(
|
||||
_empty_windowed(),
|
||||
_make_entry(path="/static/../../etc/passwd"),
|
||||
)
|
||||
assert medium.severity in {"MEDIUM", "HIGH"}
|
||||
|
||||
high = ENGINE.score_request(
|
||||
_empty_windowed(),
|
||||
_make_entry(
|
||||
path="/users",
|
||||
query_string="id=1' UNION SELECT username FROM users--",
|
||||
),
|
||||
)
|
||||
assert high.severity == "HIGH"
|
||||
|
||||
|
||||
def test_result_has_component_scores() -> None:
|
||||
"""
|
||||
RuleResult includes individual scores per triggered rule.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/users",
|
||||
query_string="id=1' OR 1=1--",
|
||||
)
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert len(result.component_scores) == len(result.matched_rules)
|
||||
for rule_name in result.matched_rules:
|
||||
assert rule_name in result.component_scores
|
||||
assert result.component_scores[rule_name] > 0.0
|
||||
|
||||
|
||||
def test_file_inclusion() -> None:
|
||||
"""
|
||||
PHP stream wrapper in query string triggers FILE_INCLUSION rule.
|
||||
"""
|
||||
entry = _make_entry(
|
||||
path="/include",
|
||||
query_string="page=php://filter/convert.base64-encode/resource=config",
|
||||
)
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert "FILE_INCLUSION" in result.matched_rules
|
||||
assert result.threat_score >= 0.5
|
||||
|
||||
|
||||
def test_double_encoding() -> None:
|
||||
"""
|
||||
Double-encoded characters trigger the DOUBLE_ENCODING rule.
|
||||
"""
|
||||
entry = _make_entry(path="/path%2527trick")
|
||||
result = ENGINE.score_request(_empty_windowed(), entry)
|
||||
assert "DOUBLE_ENCODING" in result.matched_rules
|
||||
|
|
@ -0,0 +1,592 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
test_features.py
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.core.features.extractor import extract_request_features
|
||||
from app.core.ingestion.parsers import ParsedLogEntry
|
||||
|
||||
FEATURE_KEYS = {
|
||||
"http_method",
|
||||
"path_depth",
|
||||
"path_entropy",
|
||||
"path_length",
|
||||
"query_string_length",
|
||||
"query_param_count",
|
||||
"has_encoded_chars",
|
||||
"has_double_encoding",
|
||||
"status_code",
|
||||
"status_class",
|
||||
"response_size",
|
||||
"hour_of_day",
|
||||
"day_of_week",
|
||||
"is_weekend",
|
||||
"ua_length",
|
||||
"ua_entropy",
|
||||
"is_known_bot",
|
||||
"is_known_scanner",
|
||||
"has_attack_pattern",
|
||||
"special_char_ratio",
|
||||
"file_extension",
|
||||
"country_code",
|
||||
"is_private_ip",
|
||||
}
|
||||
|
||||
|
||||
def _make_entry(
|
||||
ip: str = "93.184.216.34",
|
||||
timestamp: datetime | None = None,
|
||||
method: str = "GET",
|
||||
path: str = "/api/v1/users",
|
||||
query_string: str = "",
|
||||
status_code: int = 200,
|
||||
response_size: int = 1234,
|
||||
referer: str = "",
|
||||
user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
|
||||
) -> ParsedLogEntry:
|
||||
"""
|
||||
Build a ParsedLogEntry with sensible defaults for testing.
|
||||
"""
|
||||
if timestamp is None:
|
||||
timestamp = datetime(2026, 2, 11, 14, 30, 0, tzinfo=timezone.utc)
|
||||
|
||||
return ParsedLogEntry(
|
||||
ip=ip,
|
||||
timestamp=timestamp,
|
||||
method=method,
|
||||
path=path,
|
||||
query_string=query_string,
|
||||
status_code=status_code,
|
||||
response_size=response_size,
|
||||
referer=referer,
|
||||
user_agent=user_agent,
|
||||
raw_line="",
|
||||
)
|
||||
|
||||
|
||||
def test_extract_returns_all_23_feature_keys() -> None:
|
||||
"""
|
||||
Feature dict contains exactly the 23 per-request keys.
|
||||
"""
|
||||
features = extract_request_features(_make_entry())
|
||||
assert set(features.keys()) == FEATURE_KEYS
|
||||
|
||||
|
||||
def test_path_depth() -> None:
|
||||
"""
|
||||
Path depth counts non-empty segments between slashes.
|
||||
"""
|
||||
assert extract_request_features(_make_entry(path="/"))["path_depth"] == 0
|
||||
assert extract_request_features(_make_entry(path="/api"))["path_depth"] == 1
|
||||
assert extract_request_features(
|
||||
_make_entry(path="/api/v1/users")
|
||||
)["path_depth"] == 3
|
||||
|
||||
|
||||
def test_path_entropy_high_vs_low() -> None:
|
||||
"""
|
||||
Random-character paths have higher entropy than simple paths.
|
||||
"""
|
||||
low = extract_request_features(
|
||||
_make_entry(path="/index.html")
|
||||
)["path_entropy"]
|
||||
high = extract_request_features(
|
||||
_make_entry(path="/x8Kp2mQz7wR4vL1n")
|
||||
)["path_entropy"]
|
||||
assert high > low
|
||||
|
||||
|
||||
def test_query_string_features() -> None:
|
||||
"""
|
||||
Query param count and length are extracted correctly.
|
||||
"""
|
||||
features = extract_request_features(
|
||||
_make_entry(query_string="page=1&sort=name&limit=50")
|
||||
)
|
||||
assert features["query_param_count"] == 3
|
||||
assert features["query_string_length"] == len("page=1&sort=name&limit=50")
|
||||
|
||||
empty = extract_request_features(_make_entry(query_string=""))
|
||||
assert empty["query_param_count"] == 0
|
||||
assert empty["query_string_length"] == 0
|
||||
|
||||
|
||||
def test_url_encoding_detection() -> None:
|
||||
"""
|
||||
Percent-encoded sequences are detected in path and query.
|
||||
"""
|
||||
encoded = extract_request_features(
|
||||
_make_entry(path="/search", query_string="q=%27OR+1%3D1")
|
||||
)
|
||||
assert encoded["has_encoded_chars"] is True
|
||||
|
||||
clean = extract_request_features(
|
||||
_make_entry(path="/index.html", query_string="")
|
||||
)
|
||||
assert clean["has_encoded_chars"] is False
|
||||
|
||||
|
||||
def test_double_encoding_detection() -> None:
|
||||
"""
|
||||
Double-encoded sequences like %2527 are flagged.
|
||||
"""
|
||||
double = extract_request_features(
|
||||
_make_entry(path="/path%2527trick")
|
||||
)
|
||||
assert double["has_double_encoding"] is True
|
||||
|
||||
single = extract_request_features(
|
||||
_make_entry(path="/path%27normal")
|
||||
)
|
||||
assert single["has_double_encoding"] is False
|
||||
|
||||
|
||||
def test_status_class() -> None:
|
||||
"""
|
||||
Status class groups status codes into Nxx buckets.
|
||||
"""
|
||||
assert extract_request_features(
|
||||
_make_entry(status_code=200)
|
||||
)["status_class"] == "2xx"
|
||||
assert extract_request_features(
|
||||
_make_entry(status_code=404)
|
||||
)["status_class"] == "4xx"
|
||||
assert extract_request_features(
|
||||
_make_entry(status_code=503)
|
||||
)["status_class"] == "5xx"
|
||||
|
||||
|
||||
def test_temporal_features() -> None:
|
||||
"""
|
||||
Hour, day of week, and weekend flag derived from timestamp.
|
||||
"""
|
||||
wednesday_2pm = datetime(2026, 2, 11, 14, 0, 0, tzinfo=timezone.utc)
|
||||
features = extract_request_features(
|
||||
_make_entry(timestamp=wednesday_2pm)
|
||||
)
|
||||
assert features["hour_of_day"] == 14
|
||||
assert features["day_of_week"] == 2
|
||||
assert features["is_weekend"] is False
|
||||
|
||||
saturday_3am = datetime(2026, 2, 14, 3, 0, 0, tzinfo=timezone.utc)
|
||||
weekend = extract_request_features(
|
||||
_make_entry(timestamp=saturday_3am)
|
||||
)
|
||||
assert weekend["hour_of_day"] == 3
|
||||
assert weekend["day_of_week"] == 5
|
||||
assert weekend["is_weekend"] is True
|
||||
|
||||
|
||||
def test_ua_bot_detection() -> None:
|
||||
"""
|
||||
Known bot user agents are flagged.
|
||||
"""
|
||||
bot = extract_request_features(
|
||||
_make_entry(
|
||||
user_agent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
|
||||
)
|
||||
)
|
||||
assert bot["is_known_bot"] is True
|
||||
|
||||
normal = extract_request_features(
|
||||
_make_entry(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
|
||||
)
|
||||
assert normal["is_known_bot"] is False
|
||||
|
||||
|
||||
def test_ua_scanner_detection() -> None:
|
||||
"""
|
||||
Known vulnerability scanner user agents are flagged.
|
||||
"""
|
||||
nikto = extract_request_features(
|
||||
_make_entry(user_agent="Mozilla/5.00 (Nikto/2.1.6)")
|
||||
)
|
||||
assert nikto["is_known_scanner"] is True
|
||||
|
||||
sqlmap = extract_request_features(
|
||||
_make_entry(user_agent="sqlmap/1.8")
|
||||
)
|
||||
assert sqlmap["is_known_scanner"] is True
|
||||
|
||||
|
||||
def test_attack_pattern_detection() -> None:
|
||||
"""
|
||||
SQLi, XSS, and path traversal patterns in paths are detected.
|
||||
"""
|
||||
sqli = extract_request_features(
|
||||
_make_entry(path="/users", query_string="id=1' OR 1=1--")
|
||||
)
|
||||
assert sqli["has_attack_pattern"] is True
|
||||
|
||||
xss = extract_request_features(
|
||||
_make_entry(path="/comment", query_string="body=<script>alert(1)</script>")
|
||||
)
|
||||
assert xss["has_attack_pattern"] is True
|
||||
|
||||
traversal = extract_request_features(
|
||||
_make_entry(path="/static/../../etc/passwd")
|
||||
)
|
||||
assert traversal["has_attack_pattern"] is True
|
||||
|
||||
clean = extract_request_features(
|
||||
_make_entry(path="/api/v1/health")
|
||||
)
|
||||
assert clean["has_attack_pattern"] is False
|
||||
|
||||
|
||||
def test_special_char_ratio() -> None:
|
||||
"""
|
||||
Paths with many non-alphanumeric characters have higher ratios.
|
||||
"""
|
||||
clean = extract_request_features(
|
||||
_make_entry(path="/api/users")
|
||||
)["special_char_ratio"]
|
||||
|
||||
noisy = extract_request_features(
|
||||
_make_entry(path="/<script>alert('xss')</script>")
|
||||
)["special_char_ratio"]
|
||||
|
||||
assert noisy > clean
|
||||
|
||||
|
||||
def test_private_ip_detection() -> None:
|
||||
"""
|
||||
RFC 1918 and loopback addresses are classified as private.
|
||||
"""
|
||||
assert extract_request_features(
|
||||
_make_entry(ip="192.168.1.1")
|
||||
)["is_private_ip"] is True
|
||||
|
||||
assert extract_request_features(
|
||||
_make_entry(ip="127.0.0.1")
|
||||
)["is_private_ip"] is True
|
||||
|
||||
assert extract_request_features(
|
||||
_make_entry(ip="8.8.8.8")
|
||||
)["is_private_ip"] is False
|
||||
|
||||
|
||||
def test_file_extension() -> None:
|
||||
"""
|
||||
File extension is extracted from the path.
|
||||
"""
|
||||
assert extract_request_features(
|
||||
_make_entry(path="/style.css")
|
||||
)["file_extension"] == ".css"
|
||||
|
||||
assert extract_request_features(
|
||||
_make_entry(path="/api/users")
|
||||
)["file_extension"] == ""
|
||||
|
||||
|
||||
def test_country_code_passthrough() -> None:
|
||||
"""
|
||||
Country code is passed through from the caller.
|
||||
"""
|
||||
features = extract_request_features(
|
||||
_make_entry(), country_code="US"
|
||||
)
|
||||
assert features["country_code"] == "US"
|
||||
|
||||
features_empty = extract_request_features(_make_entry())
|
||||
assert features_empty["country_code"] == ""
|
||||
|
||||
|
||||
import time
|
||||
|
||||
import fakeredis.aioredis
|
||||
import pytest
|
||||
|
||||
from app.core.features.aggregator import WindowAggregator
|
||||
|
||||
AGGREGATOR_KEYS = {
|
||||
"req_count_1m",
|
||||
"req_count_5m",
|
||||
"req_count_10m",
|
||||
"error_rate_5m",
|
||||
"unique_paths_5m",
|
||||
"unique_uas_10m",
|
||||
"method_entropy_5m",
|
||||
"avg_response_size_5m",
|
||||
"status_diversity_5m",
|
||||
"path_depth_variance_5m",
|
||||
"inter_request_time_mean",
|
||||
"inter_request_time_std",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def aggregator():
|
||||
"""
|
||||
WindowAggregator backed by an in-memory fake Redis.
|
||||
"""
|
||||
redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
yield WindowAggregator(redis)
|
||||
await redis.aclose()
|
||||
|
||||
|
||||
async def _record(
|
||||
agg: WindowAggregator,
|
||||
ip: str = "10.0.0.1",
|
||||
request_id: str = "r-001",
|
||||
path: str = "/api/users",
|
||||
path_depth: int = 2,
|
||||
method: str = "GET",
|
||||
status_code: int = 200,
|
||||
user_agent: str = "Mozilla/5.0",
|
||||
response_size: int = 1024,
|
||||
timestamp: float | None = None,
|
||||
) -> dict[str, float]:
|
||||
"""
|
||||
Shorthand for record_and_aggregate with sensible defaults.
|
||||
"""
|
||||
return await agg.record_and_aggregate(
|
||||
ip=ip,
|
||||
request_id=request_id,
|
||||
path=path,
|
||||
path_depth=path_depth,
|
||||
method=method,
|
||||
status_code=status_code,
|
||||
user_agent=user_agent,
|
||||
response_size=response_size,
|
||||
timestamp=timestamp or time.time(),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_single_request(aggregator) -> None:
|
||||
"""
|
||||
A single request yields count of 1.
|
||||
"""
|
||||
result = await _record(aggregator)
|
||||
assert set(result.keys()) == AGGREGATOR_KEYS
|
||||
assert result["req_count_1m"] == 1
|
||||
assert result["req_count_5m"] == 1
|
||||
assert result["req_count_10m"] == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_ten_requests(aggregator) -> None:
|
||||
"""
|
||||
Ten requests within 30 seconds all count in the 1-minute window.
|
||||
"""
|
||||
now = time.time()
|
||||
result = None
|
||||
for i in range(10):
|
||||
result = await _record(
|
||||
aggregator,
|
||||
request_id=f"r-{i:03d}",
|
||||
timestamp=now - 30 + i * 3,
|
||||
)
|
||||
assert result is not None
|
||||
assert result["req_count_1m"] == 10
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_error_rate(aggregator) -> None:
|
||||
"""
|
||||
Error rate is the ratio of 4xx/5xx responses.
|
||||
"""
|
||||
now = time.time()
|
||||
for i in range(8):
|
||||
await _record(
|
||||
aggregator,
|
||||
request_id=f"ok-{i}",
|
||||
status_code=200,
|
||||
timestamp=now - 60 + i,
|
||||
)
|
||||
for i in range(2):
|
||||
result = await _record(
|
||||
aggregator,
|
||||
request_id=f"err-{i}",
|
||||
status_code=404,
|
||||
timestamp=now - 10 + i,
|
||||
)
|
||||
assert result["error_rate_5m"] == pytest.approx(0.2, abs=0.01)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_unique_paths(aggregator) -> None:
|
||||
"""
|
||||
Unique paths counts distinct URL paths in the window.
|
||||
"""
|
||||
now = time.time()
|
||||
paths = ["/api/users", "/api/posts", "/api/users", "/api/health"]
|
||||
result = None
|
||||
for i, p in enumerate(paths):
|
||||
result = await _record(
|
||||
aggregator,
|
||||
request_id=f"r-{i}",
|
||||
path=p,
|
||||
timestamp=now - 10 + i,
|
||||
)
|
||||
assert result is not None
|
||||
assert result["unique_paths_5m"] == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_unique_uas(aggregator) -> None:
|
||||
"""
|
||||
Unique UAs counts distinct user agents in the 10-minute window.
|
||||
"""
|
||||
now = time.time()
|
||||
uas = ["Mozilla/5.0", "curl/8.0", "Mozilla/5.0", "python-httpx/0.28"]
|
||||
result = None
|
||||
for i, ua in enumerate(uas):
|
||||
result = await _record(
|
||||
aggregator,
|
||||
request_id=f"r-{i}",
|
||||
user_agent=ua,
|
||||
timestamp=now - 10 + i,
|
||||
)
|
||||
assert result is not None
|
||||
assert result["unique_uas_10m"] == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_ttl_set(aggregator) -> None:
|
||||
"""
|
||||
All Redis keys are set with a 900-second TTL.
|
||||
"""
|
||||
await _record(aggregator, ip="5.5.5.5")
|
||||
ttl = await aggregator._redis.ttl("ip:5.5.5.5:requests")
|
||||
assert 0 < ttl <= 900
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aggregator_window_boundary(aggregator) -> None:
|
||||
"""
|
||||
Requests outside the 1-minute window are excluded from req_count_1m
|
||||
but still counted in req_count_5m.
|
||||
"""
|
||||
now = time.time()
|
||||
await _record(
|
||||
aggregator,
|
||||
request_id="old",
|
||||
timestamp=now - 120,
|
||||
)
|
||||
result = await _record(
|
||||
aggregator,
|
||||
request_id="new",
|
||||
timestamp=now,
|
||||
)
|
||||
assert result["req_count_1m"] == 1
|
||||
assert result["req_count_5m"] == 2
|
||||
|
||||
|
||||
from app.core.features.encoder import encode_for_inference
|
||||
from app.core.features.mappings import FEATURE_ORDER, METHOD_MAP, STATUS_CLASS_MAP
|
||||
|
||||
|
||||
def _full_features() -> dict[str, int | float | bool | str]:
|
||||
"""
|
||||
Build a complete 35-key feature dict with realistic values.
|
||||
"""
|
||||
return {
|
||||
"http_method": "GET",
|
||||
"path_depth": 3,
|
||||
"path_entropy": 3.12,
|
||||
"path_length": 14,
|
||||
"query_string_length": 6,
|
||||
"query_param_count": 1,
|
||||
"has_encoded_chars": False,
|
||||
"has_double_encoding": False,
|
||||
"status_code": 200,
|
||||
"status_class": "2xx",
|
||||
"response_size": 1234,
|
||||
"hour_of_day": 14,
|
||||
"day_of_week": 2,
|
||||
"is_weekend": False,
|
||||
"ua_length": 42,
|
||||
"ua_entropy": 4.01,
|
||||
"is_known_bot": False,
|
||||
"is_known_scanner": False,
|
||||
"has_attack_pattern": False,
|
||||
"special_char_ratio": 0.21,
|
||||
"file_extension": ".html",
|
||||
"country_code": "US",
|
||||
"is_private_ip": False,
|
||||
"req_count_1m": 5.0,
|
||||
"req_count_5m": 20.0,
|
||||
"req_count_10m": 45.0,
|
||||
"error_rate_5m": 0.1,
|
||||
"unique_paths_5m": 8.0,
|
||||
"unique_uas_10m": 2.0,
|
||||
"method_entropy_5m": 0.5,
|
||||
"avg_response_size_5m": 2048.0,
|
||||
"status_diversity_5m": 3.0,
|
||||
"path_depth_variance_5m": 1.2,
|
||||
"inter_request_time_mean": 250.0,
|
||||
"inter_request_time_std": 80.0,
|
||||
}
|
||||
|
||||
|
||||
def test_encoder_output_shape_and_type() -> None:
|
||||
"""
|
||||
Encoded vector has exactly 35 float elements.
|
||||
"""
|
||||
result = encode_for_inference(_full_features())
|
||||
assert len(result) == 35
|
||||
assert all(isinstance(v, float) for v in result)
|
||||
|
||||
|
||||
def test_encoder_method_ordinal() -> None:
|
||||
"""
|
||||
HTTP methods map to deterministic ordinal indices.
|
||||
"""
|
||||
features = _full_features()
|
||||
features["http_method"] = "GET"
|
||||
vec = encode_for_inference(features)
|
||||
assert vec[FEATURE_ORDER.index("http_method")] == float(METHOD_MAP["GET"])
|
||||
|
||||
features["http_method"] = "POST"
|
||||
vec = encode_for_inference(features)
|
||||
assert vec[FEATURE_ORDER.index("http_method")] == float(METHOD_MAP["POST"])
|
||||
|
||||
|
||||
def test_encoder_status_class_ordinal() -> None:
|
||||
"""
|
||||
Status classes map to deterministic ordinal indices.
|
||||
"""
|
||||
features = _full_features()
|
||||
features["status_class"] = "4xx"
|
||||
vec = encode_for_inference(features)
|
||||
idx = FEATURE_ORDER.index("status_class")
|
||||
assert vec[idx] == float(STATUS_CLASS_MAP["4xx"])
|
||||
|
||||
|
||||
def test_encoder_boolean_to_float() -> None:
|
||||
"""
|
||||
Boolean features encode to 0.0 or 1.0.
|
||||
"""
|
||||
features = _full_features()
|
||||
features["is_known_bot"] = True
|
||||
features["is_weekend"] = False
|
||||
vec = encode_for_inference(features)
|
||||
assert vec[FEATURE_ORDER.index("is_known_bot")] == 1.0
|
||||
assert vec[FEATURE_ORDER.index("is_weekend")] == 0.0
|
||||
|
||||
|
||||
def test_encoder_numerical_passthrough() -> None:
|
||||
"""
|
||||
Numerical features pass through as raw float values.
|
||||
"""
|
||||
features = _full_features()
|
||||
vec = encode_for_inference(features)
|
||||
assert vec[FEATURE_ORDER.index("path_depth")] == 3.0
|
||||
assert vec[FEATURE_ORDER.index("response_size")] == 1234.0
|
||||
assert vec[FEATURE_ORDER.index("req_count_1m")] == 5.0
|
||||
|
||||
|
||||
def test_encoder_unknown_categorical() -> None:
|
||||
"""
|
||||
Unknown categorical values fall back to 0.
|
||||
"""
|
||||
features = _full_features()
|
||||
features["http_method"] = "BREW"
|
||||
features["status_class"] = "9xx"
|
||||
vec = encode_for_inference(features)
|
||||
assert vec[FEATURE_ORDER.index("http_method")] == 0.0
|
||||
assert vec[FEATURE_ORDER.index("status_class")] == 0.0
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
test_geoip.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.enrichment.geoip import GeoIPService, GeoResult
|
||||
|
||||
|
||||
def _mock_city_response(
|
||||
country_iso: str = "US",
|
||||
city_name: str = "Los Angeles",
|
||||
lat: float = 34.0522,
|
||||
lon: float = -118.2437,
|
||||
) -> MagicMock:
|
||||
"""
|
||||
Build a mock geoip2 City response object.
|
||||
"""
|
||||
response = MagicMock()
|
||||
response.country.iso_code = country_iso
|
||||
response.city.name = city_name
|
||||
response.location.latitude = lat
|
||||
response.location.longitude = lon
|
||||
return response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_reader() -> MagicMock:
|
||||
"""
|
||||
A mock geoip2 database reader.
|
||||
"""
|
||||
reader = MagicMock()
|
||||
reader.city.return_value = _mock_city_response()
|
||||
return reader
|
||||
|
||||
|
||||
def test_geo_result_fields() -> None:
|
||||
"""
|
||||
GeoResult stores country, city, latitude, and longitude.
|
||||
"""
|
||||
result = GeoResult(country="US", city="Seattle", lat=47.6, lon=-122.3)
|
||||
assert result.country == "US"
|
||||
assert result.city == "Seattle"
|
||||
assert result.lat == 47.6
|
||||
assert result.lon == -122.3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_returns_geo_result(mock_reader) -> None:
|
||||
"""
|
||||
Successful lookup returns a populated GeoResult.
|
||||
"""
|
||||
service = GeoIPService.__new__(GeoIPService)
|
||||
service._reader = mock_reader
|
||||
|
||||
result = await service.lookup("8.8.8.8")
|
||||
assert result is not None
|
||||
assert result.country == "US"
|
||||
assert result.city == "Los Angeles"
|
||||
assert result.lat == pytest.approx(34.0522)
|
||||
assert result.lon == pytest.approx(-118.2437)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_private_ip_returns_none(mock_reader) -> None:
|
||||
"""
|
||||
Private/loopback IPs return None without hitting the reader.
|
||||
"""
|
||||
service = GeoIPService.__new__(GeoIPService)
|
||||
service._reader = mock_reader
|
||||
|
||||
assert await service.lookup("192.168.1.1") is None
|
||||
assert await service.lookup("127.0.0.1") is None
|
||||
assert await service.lookup("10.0.0.1") is None
|
||||
mock_reader.city.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_address_not_found_returns_none(mock_reader) -> None:
|
||||
"""
|
||||
AddressNotFoundError from the reader returns None.
|
||||
"""
|
||||
from geoip2.errors import AddressNotFoundError
|
||||
|
||||
mock_reader.city.side_effect = AddressNotFoundError("8.8.8.8")
|
||||
service = GeoIPService.__new__(GeoIPService)
|
||||
service._reader = mock_reader
|
||||
|
||||
assert await service.lookup("8.8.8.8") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_no_reader_returns_none() -> None:
|
||||
"""
|
||||
When no .mmdb file is available, all lookups return None.
|
||||
"""
|
||||
service = GeoIPService.__new__(GeoIPService)
|
||||
service._reader = None
|
||||
|
||||
assert await service.lookup("8.8.8.8") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lookup_missing_city_name(mock_reader) -> None:
|
||||
"""
|
||||
Responses with None city name are handled gracefully.
|
||||
"""
|
||||
mock_reader.city.return_value = _mock_city_response(
|
||||
city_name=None, lat=0.0, lon=0.0
|
||||
)
|
||||
service = GeoIPService.__new__(GeoIPService)
|
||||
service._reader = mock_reader
|
||||
|
||||
result = await service.lookup("1.1.1.1")
|
||||
assert result is not None
|
||||
assert result.country == "US"
|
||||
assert result.city is None
|
||||
|
||||
|
||||
def test_service_init_missing_db(tmp_path) -> None:
|
||||
"""
|
||||
Initializing with a non-existent .mmdb file sets reader to None.
|
||||
"""
|
||||
service = GeoIPService(db_path=str(tmp_path / "missing.mmdb"))
|
||||
assert service._reader is None
|
||||
|
||||
|
||||
def test_service_init_valid_db(tmp_path) -> None:
|
||||
"""
|
||||
Initializing with a valid .mmdb path opens the reader.
|
||||
"""
|
||||
fake_mmdb = tmp_path / "GeoLite2-City.mmdb"
|
||||
fake_mmdb.touch()
|
||||
|
||||
with patch("app.core.enrichment.geoip.geoip2.database.Reader") as mock_cls:
|
||||
mock_cls.return_value = MagicMock()
|
||||
service = GeoIPService(db_path=str(fake_mmdb))
|
||||
assert service._reader is not None
|
||||
mock_cls.assert_called_once_with(str(fake_mmdb))
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
test_parsers.py
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.core.ingestion.parsers import ParsedLogEntry, parse_combined
|
||||
|
||||
|
||||
def test_parse_standard_combined_line() -> None:
|
||||
"""
|
||||
Parse a standard nginx combined log line into all fields.
|
||||
"""
|
||||
line = (
|
||||
'93.184.216.34 - - [11/Feb/2026:14:30:00 +0000] '
|
||||
'"GET /api/users?page=1 HTTP/1.1" 200 1234 '
|
||||
'"https://example.com" '
|
||||
'"Mozilla/5.0 (Windows NT 10.0; Win64; x64)"'
|
||||
)
|
||||
result = parse_combined(line)
|
||||
|
||||
assert result is not None
|
||||
assert isinstance(result, ParsedLogEntry)
|
||||
assert result.ip == "93.184.216.34"
|
||||
assert result.timestamp == datetime(2026, 2, 11, 14, 30, 0, tzinfo=timezone.utc)
|
||||
assert result.method == "GET"
|
||||
assert result.path == "/api/users"
|
||||
assert result.query_string == "page=1"
|
||||
assert result.status_code == 200
|
||||
assert result.response_size == 1234
|
||||
assert result.referer == "https://example.com"
|
||||
assert result.user_agent == "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
|
||||
assert result.raw_line == line
|
||||
|
||||
|
||||
def test_parse_ipv6_address() -> None:
|
||||
"""
|
||||
Parse a line with an IPv6 source address.
|
||||
"""
|
||||
line = (
|
||||
'::1 - - [11/Feb/2026:14:30:00 +0000] '
|
||||
'"GET / HTTP/1.1" 200 612 "-" "curl/8.0"'
|
||||
)
|
||||
result = parse_combined(line)
|
||||
|
||||
assert result is not None
|
||||
assert result.ip == "::1"
|
||||
assert result.method == "GET"
|
||||
assert result.path == "/"
|
||||
assert result.query_string == ""
|
||||
|
||||
|
||||
def test_parse_missing_referer() -> None:
|
||||
"""
|
||||
A dash referer is normalized to an empty string.
|
||||
"""
|
||||
line = (
|
||||
'10.0.0.1 - - [11/Feb/2026:08:15:42 +0000] '
|
||||
'"POST /login HTTP/1.1" 302 0 "-" "Mozilla/5.0"'
|
||||
)
|
||||
result = parse_combined(line)
|
||||
|
||||
assert result is not None
|
||||
assert result.referer == ""
|
||||
assert result.method == "POST"
|
||||
assert result.status_code == 302
|
||||
|
||||
|
||||
def test_parse_complex_query_string() -> None:
|
||||
"""
|
||||
Query strings with multiple parameters and special characters.
|
||||
"""
|
||||
line = (
|
||||
'93.184.216.34 - - [11/Feb/2026:14:30:00 +0000] '
|
||||
'"GET /search?q=hello+world&lang=en&page=2&sort=relevance HTTP/1.1" '
|
||||
'200 5678 "https://example.com/search" "Mozilla/5.0"'
|
||||
)
|
||||
result = parse_combined(line)
|
||||
|
||||
assert result is not None
|
||||
assert result.path == "/search"
|
||||
assert result.query_string == "q=hello+world&lang=en&page=2&sort=relevance"
|
||||
|
||||
|
||||
def test_parse_malformed_line_returns_none() -> None:
|
||||
"""
|
||||
Malformed lines return None instead of raising.
|
||||
"""
|
||||
assert parse_combined("this is not a valid log line") is None
|
||||
|
||||
|
||||
def test_parse_empty_line_returns_none() -> None:
|
||||
"""
|
||||
Empty input returns None.
|
||||
"""
|
||||
assert parse_combined("") is None
|
||||
|
||||
|
||||
def test_parse_dash_response_size() -> None:
|
||||
"""
|
||||
A dash response size (e.g. HEAD 304) is normalized to zero.
|
||||
"""
|
||||
line = (
|
||||
'1.2.3.4 - - [11/Feb/2026:10:00:00 +0000] '
|
||||
'"HEAD / HTTP/1.1" 304 - "-" "Mozilla/5.0"'
|
||||
)
|
||||
result = parse_combined(line)
|
||||
|
||||
assert result is not None
|
||||
assert result.response_size == 0
|
||||
assert result.status_code == 304
|
||||
|
||||
|
||||
def test_parse_full_ipv6_address() -> None:
|
||||
"""
|
||||
Parse a line with a full-length IPv6 address.
|
||||
"""
|
||||
line = (
|
||||
'2001:0db8:85a3:0000:0000:8a2e:0370:7334 - - '
|
||||
'[11/Feb/2026:14:30:00 +0000] "GET /api/v1/health HTTP/2.0" '
|
||||
'200 256 "-" "python-httpx/0.28"'
|
||||
)
|
||||
result = parse_combined(line)
|
||||
|
||||
assert result is not None
|
||||
assert result.ip == "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
|
||||
assert result.path == "/api/v1/health"
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
"""
|
||||
©AngelaMos | 2026
|
||||
test_pipeline.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import fakeredis.aioredis
|
||||
import pytest
|
||||
|
||||
from app.core.detection.rules import RuleEngine
|
||||
from app.core.ingestion.pipeline import Pipeline, ScoredRequest
|
||||
|
||||
VALID_LINE = (
|
||||
'93.184.216.34 - - [11/Feb/2026:14:30:00 +0000] '
|
||||
'"GET /api/v1/users HTTP/1.1" 200 1234 '
|
||||
'"https://example.com" '
|
||||
'"Mozilla/5.0 (Windows NT 10.0; Win64; x64)"'
|
||||
)
|
||||
|
||||
SQLI_LINE = (
|
||||
'93.184.216.34 - - [11/Feb/2026:14:30:01 +0000] '
|
||||
'"GET /users?id=1%27OR%201=1-- HTTP/1.1" 200 512 '
|
||||
'"-" "Mozilla/5.0"'
|
||||
)
|
||||
|
||||
|
||||
async def _make_pipeline(
|
||||
results: list[ScoredRequest],
|
||||
raw_queue_size: int = 100,
|
||||
parsed_queue_size: int = 100,
|
||||
feature_queue_size: int = 100,
|
||||
alert_queue_size: int = 100,
|
||||
) -> Pipeline:
|
||||
"""
|
||||
Build a Pipeline wired to an in-memory Redis and a results collector.
|
||||
"""
|
||||
redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
|
||||
async def collect(sr: ScoredRequest) -> None:
|
||||
results.append(sr)
|
||||
|
||||
pipeline = Pipeline(
|
||||
redis_client=redis,
|
||||
rule_engine=RuleEngine(),
|
||||
on_result=collect,
|
||||
raw_queue_size=raw_queue_size,
|
||||
parsed_queue_size=parsed_queue_size,
|
||||
feature_queue_size=feature_queue_size,
|
||||
alert_queue_size=alert_queue_size,
|
||||
)
|
||||
await pipeline.start()
|
||||
return pipeline
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_end_to_end_valid_line() -> None:
|
||||
"""
|
||||
A valid log line flows through all 4 stages and produces a scored result.
|
||||
"""
|
||||
results: list[ScoredRequest] = []
|
||||
pipeline = await _make_pipeline(results)
|
||||
|
||||
await pipeline.raw_queue.put(VALID_LINE)
|
||||
await pipeline.stop()
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].entry.ip == "93.184.216.34"
|
||||
assert results[0].entry.method == "GET"
|
||||
assert len(results[0].feature_vector) == 35
|
||||
assert results[0].rule_result.severity == "LOW"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_malformed_line_dropped() -> None:
|
||||
"""
|
||||
Malformed lines are dropped at the parse stage without crashing.
|
||||
"""
|
||||
results: list[ScoredRequest] = []
|
||||
pipeline = await _make_pipeline(results)
|
||||
|
||||
await pipeline.raw_queue.put("this is not a valid log line")
|
||||
await pipeline.raw_queue.put(VALID_LINE)
|
||||
await pipeline.stop()
|
||||
|
||||
assert len(results) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_backpressure_with_tiny_queues() -> None:
|
||||
"""
|
||||
Items flow through correctly even when all queues have maxsize=1.
|
||||
"""
|
||||
results: list[ScoredRequest] = []
|
||||
pipeline = await _make_pipeline(
|
||||
results,
|
||||
raw_queue_size=1,
|
||||
parsed_queue_size=1,
|
||||
feature_queue_size=1,
|
||||
alert_queue_size=1,
|
||||
)
|
||||
|
||||
for _ in range(5):
|
||||
await pipeline.raw_queue.put(VALID_LINE)
|
||||
|
||||
await pipeline.stop()
|
||||
assert len(results) == 5
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_shutdown_drains_and_exits() -> None:
|
||||
"""
|
||||
Calling stop() drains remaining items and all tasks exit cleanly.
|
||||
"""
|
||||
results: list[ScoredRequest] = []
|
||||
pipeline = await _make_pipeline(results)
|
||||
|
||||
await pipeline.raw_queue.put(VALID_LINE)
|
||||
await pipeline.raw_queue.put(VALID_LINE)
|
||||
await pipeline.stop()
|
||||
|
||||
assert len(results) == 2
|
||||
assert all(t.done() for t in pipeline._tasks)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attack_line_scored_high() -> None:
|
||||
"""
|
||||
A SQLi payload in the log line is scored as HIGH by the rule engine.
|
||||
"""
|
||||
results: list[ScoredRequest] = []
|
||||
pipeline = await _make_pipeline(results)
|
||||
|
||||
await pipeline.raw_queue.put(SQLI_LINE)
|
||||
await pipeline.stop()
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].rule_result.severity == "HIGH"
|
||||
assert "SQL_INJECTION" in results[0].rule_result.matched_rules
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,110 @@
|
|||
# ©AngelaMos | 2026
|
||||
# Production Docker Compose
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-alpine
|
||||
container_name: vigil-postgres
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-angelusvigil}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-vigil}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD required}
|
||||
POSTGRES_INITDB_ARGS: "-E UTF8 --locale=C"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
networks:
|
||||
- vigil_network
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-vigil} -d ${POSTGRES_DB:-angelusvigil}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: always
|
||||
|
||||
redis:
|
||||
image: redis:7.4-alpine
|
||||
container_name: vigil-redis
|
||||
command: redis-server /usr/local/etc/redis/redis.conf
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
- ./infra/redis/redis.conf:/usr/local/etc/redis/redis.conf:ro
|
||||
networks:
|
||||
- vigil_network
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 5s
|
||||
restart: always
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/docker/fastapi.prod
|
||||
container_name: vigil-backend
|
||||
environment:
|
||||
ENV: ${ENV:-production}
|
||||
DEBUG: ${DEBUG:-false}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
API_KEY: ${API_KEY:?API_KEY required}
|
||||
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:-vigil}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-angelusvigil}
|
||||
REDIS_URL: ${REDIS_URL:-redis://redis:6379}
|
||||
NGINX_LOG_PATH: /var/log/nginx/access.log
|
||||
GEOIP_DB_PATH: /usr/share/GeoIP/GeoLite2-City.mmdb
|
||||
volumes:
|
||||
- nginx_logs:/var/log/nginx:ro
|
||||
- geoip_data:/usr/share/GeoIP:ro
|
||||
- model_data:/app/data/models
|
||||
expose:
|
||||
- "8000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- vigil_network
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
restart: always
|
||||
|
||||
geoip-updater:
|
||||
image: maxmindinc/geoipupdate:latest
|
||||
container_name: vigil-geoip
|
||||
environment:
|
||||
GEOIPUPDATE_ACCOUNT_ID: ${GEOIP_ACCOUNT_ID:?GEOIP_ACCOUNT_ID required}
|
||||
GEOIPUPDATE_LICENSE_KEY: ${GEOIP_LICENSE_KEY:?GEOIP_LICENSE_KEY required}
|
||||
GEOIPUPDATE_EDITION_IDS: "GeoLite2-City"
|
||||
GEOIPUPDATE_FREQUENCY: "168"
|
||||
volumes:
|
||||
- geoip_data:/usr/share/GeoIP
|
||||
networks:
|
||||
- vigil_network
|
||||
restart: always
|
||||
|
||||
networks:
|
||||
vigil_network:
|
||||
driver: bridge
|
||||
name: vigil_network
|
||||
certgames_net:
|
||||
external: true
|
||||
name: certgames_default
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
name: vigil_postgres_data
|
||||
redis_data:
|
||||
name: vigil_redis_data
|
||||
geoip_data:
|
||||
name: vigil_geoip_data
|
||||
model_data:
|
||||
name: vigil_model_data
|
||||
nginx_logs:
|
||||
external: true
|
||||
name: certgames_nginx_logs
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
# ©AngelaMos | 2026
|
||||
# Development Docker Compose
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18-alpine
|
||||
container_name: vigil-postgres-dev
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-angelusvigil}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-vigil}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD required}
|
||||
POSTGRES_INITDB_ARGS: "-E UTF8 --locale=C"
|
||||
volumes:
|
||||
- postgres_dev_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "${POSTGRES_HOST_PORT:-16969}:5432"
|
||||
networks:
|
||||
- vigil_network_dev
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-vigil} -d ${POSTGRES_DB:-angelusvigil}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:7.4-alpine
|
||||
container_name: vigil-redis-dev
|
||||
command: redis-server /usr/local/etc/redis/redis.conf
|
||||
volumes:
|
||||
- redis_dev_data:/data
|
||||
- ./infra/redis/redis.conf:/usr/local/etc/redis/redis.conf:ro
|
||||
ports:
|
||||
- "${REDIS_HOST_PORT:-26969}:6379"
|
||||
networks:
|
||||
- vigil_network_dev
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/docker/fastapi.dev
|
||||
container_name: vigil-backend-dev
|
||||
environment:
|
||||
ENV: ${ENV:-development}
|
||||
DEBUG: ${DEBUG:-true}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-DEBUG}
|
||||
API_KEY: ${API_KEY:-dev-api-key}
|
||||
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:-vigil}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-angelusvigil}
|
||||
REDIS_URL: ${REDIS_URL:-redis://redis:6379}
|
||||
NGINX_LOG_PATH: /var/log/nginx/access.log
|
||||
GEOIP_DB_PATH: /usr/share/GeoIP/GeoLite2-City.mmdb
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- /app/.venv
|
||||
- /app/__pycache__
|
||||
- ./data/sample-logs:/var/log/nginx:ro
|
||||
- geoip_dev_data:/usr/share/GeoIP:ro
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- vigil_network_dev
|
||||
ports:
|
||||
- "${BACKEND_HOST_PORT:-36969}:8000"
|
||||
restart: unless-stopped
|
||||
|
||||
geoip-updater:
|
||||
image: maxmindinc/geoipupdate:latest
|
||||
container_name: vigil-geoip-dev
|
||||
environment:
|
||||
GEOIPUPDATE_ACCOUNT_ID: ${GEOIP_ACCOUNT_ID:-0}
|
||||
GEOIPUPDATE_LICENSE_KEY: ${GEOIP_LICENSE_KEY:-placeholder}
|
||||
GEOIPUPDATE_EDITION_IDS: "GeoLite2-City"
|
||||
GEOIPUPDATE_FREQUENCY: "168"
|
||||
volumes:
|
||||
- geoip_dev_data:/usr/share/GeoIP
|
||||
networks:
|
||||
- vigil_network_dev
|
||||
|
||||
networks:
|
||||
vigil_network_dev:
|
||||
driver: bridge
|
||||
name: vigil_network_dev
|
||||
|
||||
volumes:
|
||||
postgres_dev_data:
|
||||
name: vigil_postgres_dev_data
|
||||
redis_dev_data:
|
||||
name: vigil_redis_dev_data
|
||||
geoip_dev_data:
|
||||
name: vigil_geoip_dev_data
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
# ©AngelaMos | 2026
|
||||
# Development FastAPI Dockerfile
|
||||
# Hot reload with uvicorn, volume mounts for code
|
||||
|
||||
FROM python:3.14-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
libpq-dev \
|
||||
curl && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY backend/pyproject.toml ./
|
||||
RUN uv pip install --system -e .[dev]
|
||||
|
||||
COPY backend/ .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "app.factory:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--reload"]
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
# ©AngelaMos | 2026
|
||||
# Production FastAPI Dockerfile
|
||||
# Multi-stage build, single uvicorn worker (pipeline runs in-process)
|
||||
|
||||
FROM python:3.14-slim AS builder
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
libpq-dev && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY backend/pyproject.toml ./
|
||||
RUN uv pip install --target /app/deps .
|
||||
|
||||
FROM python:3.14-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
libpq5 \
|
||||
curl && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
useradd -m -u 1000 appuser
|
||||
|
||||
COPY --from=builder /app/deps /home/appuser/.local/lib/python3.14/site-packages
|
||||
ENV PYTHONPATH=/home/appuser/.local/lib/python3.14/site-packages:$PYTHONPATH \
|
||||
PATH=/home/appuser/.local/lib/python3.14/site-packages/bin:$PATH
|
||||
|
||||
COPY backend/ .
|
||||
|
||||
RUN mkdir -p /app/data/models && \
|
||||
chown -R appuser:appuser /app
|
||||
USER appuser
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD curl -f http://localhost:8000/health || exit 1
|
||||
|
||||
CMD ["uvicorn", "app.factory:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"]
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
# ©AngelaMos | 2026
|
||||
# redis.conf
|
||||
|
||||
bind 0.0.0.0
|
||||
|
||||
protected-mode yes
|
||||
|
||||
rename-command FLUSHALL ""
|
||||
rename-command FLUSHDB ""
|
||||
rename-command CONFIG ""
|
||||
rename-command SHUTDOWN ""
|
||||
rename-command MONITOR ""
|
||||
rename-command DEBUG ""
|
||||
rename-command SLAVEOF ""
|
||||
rename-command MIGRATE ""
|
||||
|
||||
loglevel notice
|
||||
|
||||
slowlog-log-slower-than 10000
|
||||
slowlog-max-len 128
|
||||
latency-monitor-threshold 100
|
||||
|
||||
appendonly yes
|
||||
appendfsync everysec
|
||||
|
||||
save 900 1
|
||||
save 300 10
|
||||
save 60 10000
|
||||
|
||||
maxmemory 2gb
|
||||
|
||||
maxmemory-policy allkeys-lru
|
||||
|
||||
maxclients 10000
|
||||
tracking-table-max-keys 1000000
|
||||
|
||||
port 6379
|
||||
|
||||
io-threads 4
|
||||
io-threads-do-reads yes
|
||||
|
||||
tcp-backlog 2048
|
||||
timeout 0
|
||||
tcp-keepalive 300
|
||||
|
||||
activedefrag yes
|
||||
active-defrag-ignore-bytes 25mb
|
||||
active-defrag-threshold-lower 5
|
||||
active-defrag-threshold-upper 20
|
||||
active-defrag-cycle-min 1
|
||||
active-defrag-cycle-max 75
|
||||
|
||||
lazyfree-lazy-eviction yes
|
||||
lazyfree-lazy-expire yes
|
||||
lazyfree-lazy-server-del yes
|
||||
replica-lazy-flush yes
|
||||
|
||||
jemalloc-bg-thread yes
|
||||
|
|
@ -0,0 +1,275 @@
|
|||
# =============================================================================
|
||||
# AngelaMos | 2026
|
||||
# Justfile - AngelusVigil AI Threat Detection
|
||||
# =============================================================================
|
||||
|
||||
set dotenv-load
|
||||
set export
|
||||
set shell := ["bash", "-uc"]
|
||||
set windows-shell := ["powershell.exe", "-NoLogo", "-Command"]
|
||||
|
||||
project := file_name(justfile_directory())
|
||||
version := `git describe --tags --always 2>/dev/null || echo "dev"`
|
||||
|
||||
# =============================================================================
|
||||
# Default
|
||||
# =============================================================================
|
||||
|
||||
default:
|
||||
@just --list --unsorted
|
||||
|
||||
# =============================================================================
|
||||
# Linting and Formatting
|
||||
# =============================================================================
|
||||
|
||||
[group('lint')]
|
||||
ruff *ARGS:
|
||||
cd backend && uv run ruff check app/ cli/ {{ARGS}}
|
||||
|
||||
[group('lint')]
|
||||
ruff-fix:
|
||||
cd backend && uv run ruff check app/ cli/ --fix
|
||||
cd backend && uv run ruff format app/ cli/
|
||||
|
||||
[group('lint')]
|
||||
ruff-format:
|
||||
cd backend && uv run ruff format app/ cli/
|
||||
|
||||
[group('lint')]
|
||||
pylint *ARGS:
|
||||
cd backend && uv run pylint app {{ARGS}}
|
||||
|
||||
[group('lint')]
|
||||
lint: ruff pylint
|
||||
|
||||
# =============================================================================
|
||||
# Type Checking
|
||||
# =============================================================================
|
||||
|
||||
[group('types')]
|
||||
mypy *ARGS:
|
||||
cd backend && uv run mypy app/ cli/ {{ARGS}}
|
||||
|
||||
[group('types')]
|
||||
typecheck: mypy
|
||||
|
||||
# =============================================================================
|
||||
# Testing
|
||||
# =============================================================================
|
||||
|
||||
[group('test')]
|
||||
pytest *ARGS:
|
||||
cd backend && uv run pytest tests/ {{ARGS}}
|
||||
|
||||
[group('test')]
|
||||
test: pytest
|
||||
|
||||
[group('test')]
|
||||
test-cov:
|
||||
cd backend && uv run pytest tests/ --cov=app --cov-report=term-missing --cov-report=html
|
||||
|
||||
# =============================================================================
|
||||
# CI / Quality
|
||||
# =============================================================================
|
||||
|
||||
[group('ci')]
|
||||
ci: lint typecheck test
|
||||
|
||||
[group('ci')]
|
||||
check: ruff mypy
|
||||
|
||||
# =============================================================================
|
||||
# Docker Compose (Production)
|
||||
# =============================================================================
|
||||
|
||||
[group('docker')]
|
||||
up *ARGS:
|
||||
docker compose up {{ARGS}}
|
||||
|
||||
[group('docker')]
|
||||
start *ARGS:
|
||||
docker compose up -d {{ARGS}}
|
||||
|
||||
[group('docker')]
|
||||
down *ARGS:
|
||||
docker compose down {{ARGS}}
|
||||
|
||||
[group('docker')]
|
||||
stop:
|
||||
docker compose stop
|
||||
|
||||
[group('docker')]
|
||||
build *ARGS:
|
||||
docker compose build {{ARGS}}
|
||||
|
||||
[group('docker')]
|
||||
rebuild:
|
||||
docker compose build --no-cache
|
||||
|
||||
[group('docker')]
|
||||
logs *SERVICE:
|
||||
docker compose logs -f {{SERVICE}}
|
||||
|
||||
[group('docker')]
|
||||
ps:
|
||||
docker compose ps
|
||||
|
||||
[group('docker')]
|
||||
shell service='backend':
|
||||
docker compose exec -it {{service}} /bin/bash
|
||||
|
||||
# =============================================================================
|
||||
# Docker Compose (Dev)
|
||||
# =============================================================================
|
||||
|
||||
[group('dev')]
|
||||
dev-up *ARGS:
|
||||
docker compose -f dev.compose.yml up {{ARGS}}
|
||||
|
||||
[group('dev')]
|
||||
dev-start *ARGS:
|
||||
docker compose -f dev.compose.yml up -d {{ARGS}}
|
||||
|
||||
[group('dev')]
|
||||
dev-down *ARGS:
|
||||
docker compose -f dev.compose.yml down {{ARGS}}
|
||||
|
||||
[group('dev')]
|
||||
dev-stop:
|
||||
docker compose -f dev.compose.yml stop
|
||||
|
||||
[group('dev')]
|
||||
dev-build *ARGS:
|
||||
docker compose -f dev.compose.yml build {{ARGS}}
|
||||
|
||||
[group('dev')]
|
||||
dev-rebuild:
|
||||
docker compose -f dev.compose.yml build --no-cache
|
||||
|
||||
[group('dev')]
|
||||
dev-logs *SERVICE:
|
||||
docker compose -f dev.compose.yml logs -f {{SERVICE}}
|
||||
|
||||
[group('dev')]
|
||||
dev-ps:
|
||||
docker compose -f dev.compose.yml ps
|
||||
|
||||
[group('dev')]
|
||||
dev-shell service='backend':
|
||||
docker compose -f dev.compose.yml exec -it {{service}} /bin/bash
|
||||
|
||||
# =============================================================================
|
||||
# Database (Docker)
|
||||
# =============================================================================
|
||||
|
||||
[group('db')]
|
||||
migrate *ARGS:
|
||||
docker compose exec backend uv run alembic upgrade {{ARGS}}
|
||||
|
||||
[group('db')]
|
||||
migration message:
|
||||
docker compose exec backend uv run alembic revision --autogenerate -m "{{message}}"
|
||||
|
||||
[group('db')]
|
||||
rollback:
|
||||
docker compose exec backend uv run alembic downgrade -1
|
||||
|
||||
[group('db')]
|
||||
db-history:
|
||||
docker compose exec backend uv run alembic history --verbose
|
||||
|
||||
[group('db')]
|
||||
db-current:
|
||||
docker compose exec backend uv run alembic current
|
||||
|
||||
# =============================================================================
|
||||
# Database (Local - no Docker)
|
||||
# =============================================================================
|
||||
|
||||
[group('db-local')]
|
||||
migrate-local *ARGS:
|
||||
cd backend && uv run alembic upgrade {{ARGS}}
|
||||
|
||||
[group('db-local')]
|
||||
migration-local message:
|
||||
cd backend && uv run alembic revision --autogenerate -m "{{message}}"
|
||||
|
||||
[group('db-local')]
|
||||
rollback-local:
|
||||
cd backend && uv run alembic downgrade -1
|
||||
|
||||
[group('db-local')]
|
||||
db-history-local:
|
||||
cd backend && uv run alembic history --verbose
|
||||
|
||||
[group('db-local')]
|
||||
db-current-local:
|
||||
cd backend && uv run alembic current
|
||||
|
||||
# =============================================================================
|
||||
# AngelusVigil CLI
|
||||
# =============================================================================
|
||||
|
||||
[group('vigil')]
|
||||
serve *ARGS:
|
||||
cd backend && uv run python -m app {{ARGS}}
|
||||
|
||||
[group('vigil')]
|
||||
vigil-config:
|
||||
cd backend && uv run vigil config
|
||||
|
||||
[group('vigil')]
|
||||
vigil-health:
|
||||
curl -sf http://localhost:8000/health | python -m json.tool
|
||||
|
||||
# =============================================================================
|
||||
# Setup
|
||||
# =============================================================================
|
||||
|
||||
[group('setup')]
|
||||
setup: setup-backend env
|
||||
@echo "Setup complete!"
|
||||
|
||||
[group('setup')]
|
||||
setup-backend:
|
||||
@echo "Setting up backend..."
|
||||
cd backend && uv sync
|
||||
@echo "Backend setup complete!"
|
||||
|
||||
[group('setup')]
|
||||
env:
|
||||
@echo "Creating .env file..."
|
||||
@if [ ! -f .env ]; then cp .env.example .env; echo "Created .env from example"; fi
|
||||
@echo ".env ready! Please update with your values."
|
||||
|
||||
# =============================================================================
|
||||
# Utilities
|
||||
# =============================================================================
|
||||
|
||||
[group('util')]
|
||||
info:
|
||||
@echo "Project: {{project}}"
|
||||
@echo "Version: {{version}}"
|
||||
@echo "OS: {{os()}} ({{arch()}})"
|
||||
|
||||
[group('util')]
|
||||
clean:
|
||||
-rm -rf backend/.mypy_cache
|
||||
-rm -rf backend/.pytest_cache
|
||||
-rm -rf backend/.ruff_cache
|
||||
-rm -rf backend/htmlcov
|
||||
-rm -rf backend/.coverage
|
||||
@echo "Cache directories cleaned"
|
||||
|
||||
[group('util')]
|
||||
[confirm("Remove all containers, volumes, and build artifacts?")]
|
||||
nuke:
|
||||
@echo "Nuking everything..."
|
||||
-docker compose -f dev.compose.yml down -v
|
||||
-docker compose down -v
|
||||
-rm -rf backend/.venv
|
||||
-rm -rf backend/__pycache__
|
||||
-rm -rf backend/.pytest_cache
|
||||
-rm -rf backend/.mypy_cache
|
||||
-rm -rf backend/.ruff_cache
|
||||
@echo "Nuke complete!"
|
||||
Loading…
Reference in New Issue