inv-k8s 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- inv_k8s-0.1.0/.github/actions/inv-k8s/action.yml +72 -0
- inv_k8s-0.1.0/.github/workflows/inv-k8s.yml +23 -0
- inv_k8s-0.1.0/.inv-k8s.yaml +17 -0
- inv_k8s-0.1.0/PKG-INFO +37 -0
- inv_k8s-0.1.0/README.md +9 -0
- inv_k8s-0.1.0/inv-k8s.sarif +42 -0
- inv_k8s-0.1.0/pyproject.toml +47 -0
- inv_k8s-0.1.0/scripts/check-incidents.ps1 +12 -0
- inv_k8s-0.1.0/src/inv_k8s/__init__.py +1 -0
- inv_k8s-0.1.0/src/inv_k8s/__main__.py +5 -0
- inv_k8s-0.1.0/src/inv_k8s/cli.py +97 -0
- inv_k8s-0.1.0/src/inv_k8s/config.py +67 -0
- inv_k8s-0.1.0/src/inv_k8s/graph.py +172 -0
- inv_k8s-0.1.0/src/inv_k8s/invariants/__init__.py +29 -0
- inv_k8s-0.1.0/src/inv_k8s/invariants/base.py +24 -0
- inv_k8s-0.1.0/src/inv_k8s/invariants/local.py +150 -0
- inv_k8s-0.1.0/src/inv_k8s/invariants/topology.py +192 -0
- inv_k8s-0.1.0/src/inv_k8s/models.py +98 -0
- inv_k8s-0.1.0/src/inv_k8s/parser.py +134 -0
- inv_k8s-0.1.0/src/inv_k8s/report.py +79 -0
- inv_k8s-0.1.0/src/inv_k8s/sarif.py +57 -0
- inv_k8s-0.1.0/tests/__init__.py +0 -0
- inv_k8s-0.1.0/tests/conftest.py +17 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/01-targetport-mismatch/README.md +10 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/01-targetport-mismatch/deployment.yaml +20 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/01-targetport-mismatch/service.yaml +11 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/02-missing-configmap/README.md +10 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/02-missing-configmap/configmap-other.yaml +7 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/02-missing-configmap/deployment.yaml +21 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/03-replicas-inversion/README.md +10 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/03-replicas-inversion/backend.yaml +32 -0
- inv_k8s-0.1.0/tests/fixtures/incidents/03-replicas-inversion/frontend.yaml +30 -0
- inv_k8s-0.1.0/tests/fixtures/topology/configmap.yaml +7 -0
- inv_k8s-0.1.0/tests/fixtures/topology/deployment.yaml +32 -0
- inv_k8s-0.1.0/tests/fixtures/topology/service.yaml +11 -0
- inv_k8s-0.1.0/tests/test_cli.py +38 -0
- inv_k8s-0.1.0/tests/test_graph.py +51 -0
- inv_k8s-0.1.0/tests/test_invariants.py +80 -0
- inv_k8s-0.1.0/tests/test_parser.py +68 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
name: "inv-k8s"
|
|
2
|
+
description: "Topology-aware invariant validator for Kubernetes manifests"
|
|
3
|
+
author: "inv-k8s"
|
|
4
|
+
branding:
|
|
5
|
+
icon: "shield"
|
|
6
|
+
color: "blue"
|
|
7
|
+
|
|
8
|
+
inputs:
|
|
9
|
+
path:
|
|
10
|
+
description: "Path to directory or file with Kubernetes manifests"
|
|
11
|
+
required: false
|
|
12
|
+
default: "."
|
|
13
|
+
severity:
|
|
14
|
+
description: "Minimum severity to fail (error|warning|info)"
|
|
15
|
+
required: false
|
|
16
|
+
default: "error"
|
|
17
|
+
config:
|
|
18
|
+
description: "Path to .inv-k8s.yaml config"
|
|
19
|
+
required: false
|
|
20
|
+
default: ""
|
|
21
|
+
sarif-file:
|
|
22
|
+
description: "Path to write SARIF report (empty = skip)"
|
|
23
|
+
required: false
|
|
24
|
+
default: "inv-k8s.sarif"
|
|
25
|
+
|
|
26
|
+
outputs:
|
|
27
|
+
sarif-file:
|
|
28
|
+
description: "Path to generated SARIF file"
|
|
29
|
+
value: ${{ steps.run.outputs.sarif-file }}
|
|
30
|
+
|
|
31
|
+
runs:
|
|
32
|
+
using: "composite"
|
|
33
|
+
steps:
|
|
34
|
+
- name: Set up Python
|
|
35
|
+
uses: actions/setup-python@v5
|
|
36
|
+
with:
|
|
37
|
+
python-version: "3.12"
|
|
38
|
+
|
|
39
|
+
- name: Install inv-k8s
|
|
40
|
+
shell: bash
|
|
41
|
+
run: |
|
|
42
|
+
python -m pip install --upgrade pip
|
|
43
|
+
pip install "inv-k8s @ git+https://github.com/YOUR_ORG/inv-k8s@main"
|
|
44
|
+
|
|
45
|
+
- name: Run inv-k8s
|
|
46
|
+
id: run
|
|
47
|
+
shell: bash
|
|
48
|
+
env:
|
|
49
|
+
INPUT_PATH: ${{ inputs.path }}
|
|
50
|
+
INPUT_SEVERITY: ${{ inputs.severity }}
|
|
51
|
+
INPUT_CONFIG: ${{ inputs.config }}
|
|
52
|
+
INPUT_SARIF: ${{ inputs.sarif-file }}
|
|
53
|
+
run: |
|
|
54
|
+
ARGS=("$INPUT_PATH" "--severity" "$INPUT_SEVERITY" "--format" "text")
|
|
55
|
+
if [ -n "$INPUT_CONFIG" ]; then
|
|
56
|
+
ARGS+=("--config" "$INPUT_CONFIG")
|
|
57
|
+
fi
|
|
58
|
+
set +e
|
|
59
|
+
python -m inv_k8s "${ARGS[@]}"
|
|
60
|
+
CODE=$?
|
|
61
|
+
set -e
|
|
62
|
+
|
|
63
|
+
if [ -n "$INPUT_SARIF" ]; then
|
|
64
|
+
python -m inv_k8s "$INPUT_PATH" --format sarif -o "$INPUT_SARIF" || true
|
|
65
|
+
echo "sarif-file=$INPUT_SARIF" >> "$GITHUB_OUTPUT"
|
|
66
|
+
fi
|
|
67
|
+
|
|
68
|
+
if [ -f "$INPUT_SARIF" ]; then
|
|
69
|
+
echo "### inv-k8s SARIF" >> "$GITHUB_STEP_SUMMARY"
|
|
70
|
+
echo "\`$INPUT_SARIF\`" >> "$GITHUB_STEP_SUMMARY"
|
|
71
|
+
fi
|
|
72
|
+
exit $CODE
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
name: Validate Kubernetes Manifests
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
validate:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- name: Run inv-k8s
|
|
14
|
+
uses: ./.github/actions/inv-k8s
|
|
15
|
+
with:
|
|
16
|
+
path: "./tests/fixtures/topology"
|
|
17
|
+
severity: "error"
|
|
18
|
+
sarif-file: "inv-k8s.sarif"
|
|
19
|
+
- name: Upload SARIF
|
|
20
|
+
if: always()
|
|
21
|
+
uses: github/codeql-action/upload-sarif@v3
|
|
22
|
+
with:
|
|
23
|
+
sarif_file: inv-k8s.sarif
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Кастомные настройки inv-k8s
|
|
2
|
+
severity_overrides:
|
|
3
|
+
TI.3: error # по умолчанию warning, здесь повышаем
|
|
4
|
+
TI.2: warning # понижаем TI.2 до warning
|
|
5
|
+
|
|
6
|
+
disabled_invariants:
|
|
7
|
+
- ЛИ.4 # отключаем проверку namespace в одном файле
|
|
8
|
+
apiVersion: apps/v1
|
|
9
|
+
kind: Deployment
|
|
10
|
+
metadata:
|
|
11
|
+
name: backend
|
|
12
|
+
spec:
|
|
13
|
+
template:
|
|
14
|
+
spec:
|
|
15
|
+
containers:
|
|
16
|
+
- name: c
|
|
17
|
+
image: app:latest # inv-k8s:ignore ЛИ.1 reason="dev only"
|
inv_k8s-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: inv-k8s
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Topology-aware invariant validator for Kubernetes manifests
|
|
5
|
+
Project-URL: Homepage, https://github.com/daratitovaa/inv-k8s
|
|
6
|
+
Project-URL: Repository, https://github.com/daratitovaa/inv-k8s
|
|
7
|
+
Project-URL: Issues, https://github.com/daratitovaa/inv-k8s/issues
|
|
8
|
+
Author: INV-K8S
|
|
9
|
+
License: MIT
|
|
10
|
+
Keywords: ci-cd,devops,k8s,kubernetes,linter,static-analysis,yaml
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: networkx>=3.2
|
|
21
|
+
Requires-Dist: pydantic>=2.6.0
|
|
22
|
+
Requires-Dist: rich>=13.7.0
|
|
23
|
+
Requires-Dist: ruamel-yaml>=0.18.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# inv-k8s
|
|
30
|
+
|
|
31
|
+
**Topology-aware invariant validator for Kubernetes manifests.**
|
|
32
|
+
|
|
33
|
+
... (полный текст README из прошлого сообщения) ...
|
|
34
|
+
|
|
35
|
+
## License
|
|
36
|
+
|
|
37
|
+
MIT
|
inv_k8s-0.1.0/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"timestamp": "2026-12-03T14:40:36Z",
|
|
3
|
+
"files_processed": 3,
|
|
4
|
+
"invariants_checked": 8,
|
|
5
|
+
"violations": [
|
|
6
|
+
{
|
|
7
|
+
"invariant_id": "TI.1",
|
|
8
|
+
"severity": "error",
|
|
9
|
+
"message": "Service/backend: targetPort 9090 not found in workload Deployment/backend",
|
|
10
|
+
"files": [
|
|
11
|
+
"service.yaml",
|
|
12
|
+
"deployment.yaml"
|
|
13
|
+
],
|
|
14
|
+
"lines": []
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"invariant_id": "TI.2",
|
|
18
|
+
"severity": "error",
|
|
19
|
+
"message": "Deployment/backend: envFrom missing ConfigMap 'missing-config'",
|
|
20
|
+
"files": [
|
|
21
|
+
"deployment.yaml"
|
|
22
|
+
],
|
|
23
|
+
"lines": []
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"invariant_id": "TI.2",
|
|
27
|
+
"severity": "warning",
|
|
28
|
+
"message": "Deployment/backend: references missing ServiceAccount 'missing-sa'",
|
|
29
|
+
"files": [
|
|
30
|
+
"deployment.yaml"
|
|
31
|
+
],
|
|
32
|
+
"lines": []
|
|
33
|
+
}
|
|
34
|
+
],
|
|
35
|
+
"parse_errors": [],
|
|
36
|
+
"summary": {
|
|
37
|
+
"total_violations": 3,
|
|
38
|
+
"errors": 2,
|
|
39
|
+
"warnings": 1,
|
|
40
|
+
"info": 0
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "inv-k8s"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Topology-aware invariant validator for Kubernetes manifests"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "INV-K8S" }]
|
|
13
|
+
keywords = ["kubernetes", "k8s", "yaml", "linter", "devops", "ci-cd", "static-analysis"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
23
|
+
]
|
|
24
|
+
dependencies = [
|
|
25
|
+
"ruamel.yaml>=0.18.0",
|
|
26
|
+
"networkx>=3.2",
|
|
27
|
+
"rich>=13.7.0",
|
|
28
|
+
"pydantic>=2.6.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["pytest>=8.0", "pytest-cov>=5.0"]
|
|
33
|
+
|
|
34
|
+
[project.scripts]
|
|
35
|
+
inv-k8s = "inv_k8s.cli:main"
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/daratitovaa/inv-k8s"
|
|
39
|
+
Repository = "https://github.com/daratitovaa/inv-k8s"
|
|
40
|
+
Issues = "https://github.com/daratitovaa/inv-k8s/issues"
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.wheel]
|
|
43
|
+
packages = ["src/inv_k8s"]
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
testpaths = ["tests"]
|
|
47
|
+
addopts = "-q"
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
$ErrorActionPreference = "Continue"
|
|
2
|
+
$incidents = Get-ChildItem tests/fixtures/incidents -Directory
|
|
3
|
+
$passed = 0
|
|
4
|
+
$total = 0
|
|
5
|
+
foreach ($inc in $incidents) {
|
|
6
|
+
$total++
|
|
7
|
+
Write-Host "`n=== $($inc.Name) ===" -ForegroundColor Cyan
|
|
8
|
+
python -m inv_k8s $inc.FullName --format text
|
|
9
|
+
if ($LASTEXITCODE -eq 1 -or $LASTEXITCODE -eq 0) { $passed++ }
|
|
10
|
+
else { Write-Host " UNEXPECTED EXIT CODE: $LASTEXITCODE" -ForegroundColor Red }
|
|
11
|
+
}
|
|
12
|
+
Write-Host "`nProcessed: $passed / $total" -ForegroundColor Green
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .config import ProjectConfig
|
|
9
|
+
from .graph import build_graph
|
|
10
|
+
from .invariants import default_invariants
|
|
11
|
+
from .models import Severity
|
|
12
|
+
from .parser import parse_directory
|
|
13
|
+
from .report import build_report, print_report, report_to_json
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SeverityOpt(str, Enum):
|
|
17
|
+
error = "error"
|
|
18
|
+
warning = "warning"
|
|
19
|
+
info = "info"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main(argv: list[str] | None = None) -> int:
|
|
23
|
+
parser = argparse.ArgumentParser(
|
|
24
|
+
prog="inv-k8s",
|
|
25
|
+
description="Topology-aware invariant validator for Kubernetes manifests",
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument("path", type=Path, help="Directory or YAML file to scan")
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"--severity", "-s", type=SeverityOpt, choices=list(SeverityOpt),
|
|
30
|
+
default=SeverityOpt.error, help="Minimum severity to fail (default: error)",
|
|
31
|
+
)
|
|
32
|
+
parser.add_argument("--output", "-o", type=Path, default=None, help="Write JSON report to file")
|
|
33
|
+
parser.add_argument("--format", "-f", choices=["text", "json", "sarif"], default="text", help="Output format")
|
|
34
|
+
parser.add_argument("--verbose", "-v", action="store_true", help="Print per-file details")
|
|
35
|
+
|
|
36
|
+
args = parser.parse_args(argv)
|
|
37
|
+
|
|
38
|
+
if not args.path.exists():
|
|
39
|
+
parser.error(f"Path does not exist: {args.path}")
|
|
40
|
+
|
|
41
|
+
min_sev = {SeverityOpt.error: 2, SeverityOpt.warning: 1, SeverityOpt.info: 0}[args.severity]
|
|
42
|
+
|
|
43
|
+
resources, parse_errors, files_count = parse_directory(args.path)
|
|
44
|
+
graph = build_graph(resources)
|
|
45
|
+
|
|
46
|
+
if args.verbose:
|
|
47
|
+
print(f"Files: {files_count}, resources: {len(resources)}, parse errors: {len(parse_errors)}")
|
|
48
|
+
print(f"Graph: {graph.g.number_of_nodes()} nodes, {graph.g.number_of_edges()} edges")
|
|
49
|
+
for e in parse_errors:
|
|
50
|
+
print(f" PARSE ERR {e.file}: {e.message}")
|
|
51
|
+
|
|
52
|
+
config = ProjectConfig.load_with_inline(args.path)
|
|
53
|
+
|
|
54
|
+
invariants = default_invariants()
|
|
55
|
+
all_violations = []
|
|
56
|
+
for inv in invariants:
|
|
57
|
+
if config.is_disabled(inv.id):
|
|
58
|
+
continue
|
|
59
|
+
for v in inv.check(resources, graph):
|
|
60
|
+
# inline-подавление
|
|
61
|
+
if any(config.is_suppressed(f, v.invariant_id) for f in v.files):
|
|
62
|
+
continue
|
|
63
|
+
# severity override
|
|
64
|
+
override = config.severity_for(v.invariant_id, v.severity.value)
|
|
65
|
+
if override != v.severity.value:
|
|
66
|
+
v = v.model_copy(update={"severity": Severity(override)})
|
|
67
|
+
all_violations.append(v)
|
|
68
|
+
|
|
69
|
+
report = build_report(
|
|
70
|
+
files_processed=files_count,
|
|
71
|
+
invariants_checked=len(invariants),
|
|
72
|
+
violations=all_violations,
|
|
73
|
+
parse_errors=parse_errors,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
if args.format == "json":
|
|
77
|
+
print(report_to_json(report))
|
|
78
|
+
elif args.format == "sarif":
|
|
79
|
+
from .sarif import report_to_sarif
|
|
80
|
+
print(report_to_sarif(report))
|
|
81
|
+
else:
|
|
82
|
+
print_report(report)
|
|
83
|
+
|
|
84
|
+
if args.output:
|
|
85
|
+
args.output.write_text(report_to_json(report), encoding="utf-8")
|
|
86
|
+
if args.format != "json":
|
|
87
|
+
print(f"JSON report saved to {args.output}")
|
|
88
|
+
|
|
89
|
+
if report.error_count > 0 and min_sev <= 2:
|
|
90
|
+
return 1
|
|
91
|
+
if report.warning_count > 0 and min_sev <= 1:
|
|
92
|
+
return 1
|
|
93
|
+
return 0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
if __name__ == "__main__":
|
|
97
|
+
sys.exit(main())
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from ruamel.yaml import YAML
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
IGNORE_PATTERN = re.compile(r"#\s*inv-k8s:ignore\s+(?P<ids>[A-ZА-Я0-9.,\s]+)(?:reason=\"(?P<reason>[^\"]*)\")?")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class IgnoreRule:
|
|
15
|
+
invariant_ids: set[str]
|
|
16
|
+
reason: str = ""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class ProjectConfig:
|
|
21
|
+
severity_overrides: dict[str, str] = field(default_factory=dict)
|
|
22
|
+
disabled_invariants: set[str] = field(default_factory=set)
|
|
23
|
+
inline_ignores: dict[str, list[IgnoreRule]] = field(default_factory=dict) # file -> rules
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def from_file(cls, path: Path) -> "ProjectConfig":
|
|
27
|
+
if not path.exists():
|
|
28
|
+
return cls()
|
|
29
|
+
yaml = YAML(typ="safe")
|
|
30
|
+
data = yaml.load(path.read_text(encoding="utf-8")) or {}
|
|
31
|
+
return cls(
|
|
32
|
+
severity_overrides=data.get("severity_overrides", {}) or {},
|
|
33
|
+
disabled_invariants=set(data.get("disabled_invariants", []) or []),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def load_with_inline(cls, root: Path, config_path: Path | None = None) -> "ProjectConfig":
|
|
38
|
+
cfg_path = config_path or (root / ".inv-k8s.yaml" if root.is_dir() else root.parent / ".inv-k8s.yaml")
|
|
39
|
+
cfg = cls.from_file(cfg_path) if cfg_path else cls()
|
|
40
|
+
# Сканируем inline-подавления по всем YAML-файлам
|
|
41
|
+
files = [root] if root.is_file() else list(root.rglob("*.yaml")) + list(root.rglob("*.yml"))
|
|
42
|
+
for f in files:
|
|
43
|
+
if not f.is_file():
|
|
44
|
+
continue
|
|
45
|
+
try:
|
|
46
|
+
text = f.read_text(encoding="utf-8", errors="replace")
|
|
47
|
+
except OSError:
|
|
48
|
+
continue
|
|
49
|
+
rules = []
|
|
50
|
+
for m in IGNORE_PATTERN.finditer(text):
|
|
51
|
+
ids = {x.strip() for x in re.split(r"[,\s]+", m.group("ids")) if x.strip()}
|
|
52
|
+
rules.append(IgnoreRule(invariant_ids=ids, reason=m.group("reason") or ""))
|
|
53
|
+
if rules:
|
|
54
|
+
cfg.inline_ignores[str(f)] = rules
|
|
55
|
+
return cfg
|
|
56
|
+
|
|
57
|
+
def is_suppressed(self, file: str, invariant_id: str) -> bool:
|
|
58
|
+
for rule in self.inline_ignores.get(file, []):
|
|
59
|
+
if invariant_id in rule.invariant_ids or "*" in rule.invariant_ids:
|
|
60
|
+
return True
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
def severity_for(self, invariant_id: str, default: str) -> str:
|
|
64
|
+
return self.severity_overrides.get(invariant_id, default)
|
|
65
|
+
|
|
66
|
+
def is_disabled(self, invariant_id: str) -> bool:
|
|
67
|
+
return invariant_id in self.disabled_invariants
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Iterable
|
|
6
|
+
|
|
7
|
+
import networkx as nx
|
|
8
|
+
|
|
9
|
+
from .models import K8sResource
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EdgeType(str, Enum):
|
|
13
|
+
ENV_FROM = "envFrom"
|
|
14
|
+
ENV_VALUE_FROM = "valueFrom"
|
|
15
|
+
VOLUME_CONFIGMAP = "volume.configMap"
|
|
16
|
+
VOLUME_SECRET = "volume.secret"
|
|
17
|
+
VOLUME_PVC = "volume.pvc"
|
|
18
|
+
SERVICE_ACCOUNT = "serviceAccount"
|
|
19
|
+
SERVICE_TARGET = "service.target" # Service -> workload
|
|
20
|
+
INGRESS_BACKEND = "ingress.backend"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Edge:
|
|
25
|
+
source: tuple[str, str, str]
|
|
26
|
+
target: tuple[str, str, str]
|
|
27
|
+
type: EdgeType
|
|
28
|
+
detail: str = ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DependencyGraph:
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self.g: nx.MultiDiGraph = nx.MultiDiGraph()
|
|
34
|
+
self._by_uid: dict[tuple[str, str, str], K8sResource] = {}
|
|
35
|
+
|
|
36
|
+
def add_resource(self, r: K8sResource) -> None:
|
|
37
|
+
self.g.add_node(r.uid, resource=r)
|
|
38
|
+
self._by_uid[r.uid] = r
|
|
39
|
+
|
|
40
|
+
def add_edge(self, src: K8sResource, dst: K8sResource, etype: EdgeType, detail: str = "") -> None:
|
|
41
|
+
self.g.add_edge(src.uid, dst.uid, key=etype.value, type=etype, detail=detail)
|
|
42
|
+
|
|
43
|
+
def get(self, uid: tuple[str, str, str]) -> K8sResource | None:
|
|
44
|
+
return self._by_uid.get(uid)
|
|
45
|
+
|
|
46
|
+
def find(self, kind: str, namespace: str, name: str) -> K8sResource | None:
|
|
47
|
+
return self._by_uid.get((kind, namespace, name))
|
|
48
|
+
|
|
49
|
+
def all_resources(self) -> Iterable[K8sResource]:
|
|
50
|
+
return self._by_uid.values()
|
|
51
|
+
|
|
52
|
+
def cycles(self) -> list[list[tuple[str, str, str]]]:
|
|
53
|
+
try:
|
|
54
|
+
return list(nx.simple_cycles(nx.DiGraph(self.g)))
|
|
55
|
+
except Exception:
|
|
56
|
+
return []
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_graph(resources: list[K8sResource]) -> DependencyGraph:
|
|
60
|
+
g = DependencyGraph()
|
|
61
|
+
for r in resources:
|
|
62
|
+
g.add_resource(r)
|
|
63
|
+
|
|
64
|
+
# Индекс: (kind, ns, name) -> resource для резолвинга ссылок
|
|
65
|
+
by_kind: dict[tuple[str, str, str], K8sResource] = {}
|
|
66
|
+
for r in resources:
|
|
67
|
+
by_kind[(r.kind, r.namespace, r.name)] = r
|
|
68
|
+
|
|
69
|
+
for r in resources:
|
|
70
|
+
ns = r.namespace
|
|
71
|
+
spec = r.pod_spec
|
|
72
|
+
|
|
73
|
+
# 1. serviceAccountName
|
|
74
|
+
if spec:
|
|
75
|
+
sa = spec.get("serviceAccountName")
|
|
76
|
+
if isinstance(sa, str) and sa:
|
|
77
|
+
target = by_kind.get(("ServiceAccount", ns, sa))
|
|
78
|
+
if target:
|
|
79
|
+
g.add_edge(r, target, EdgeType.SERVICE_ACCOUNT, sa)
|
|
80
|
+
|
|
81
|
+
# 2. volumes
|
|
82
|
+
volumes = spec.get("volumes") or []
|
|
83
|
+
if isinstance(volumes, list):
|
|
84
|
+
for v in volumes:
|
|
85
|
+
if not isinstance(v, dict):
|
|
86
|
+
continue
|
|
87
|
+
if "configMap" in v:
|
|
88
|
+
cm = v["configMap"].get("name") if isinstance(v["configMap"], dict) else None
|
|
89
|
+
if cm:
|
|
90
|
+
t = by_kind.get(("ConfigMap", ns, cm))
|
|
91
|
+
if t:
|
|
92
|
+
g.add_edge(r, t, EdgeType.VOLUME_CONFIGMAP, cm)
|
|
93
|
+
if "secret" in v:
|
|
94
|
+
s = v["secret"].get("secretName") if isinstance(v["secret"], dict) else None
|
|
95
|
+
if s:
|
|
96
|
+
t = by_kind.get(("Secret", ns, s))
|
|
97
|
+
if t:
|
|
98
|
+
g.add_edge(r, t, EdgeType.VOLUME_SECRET, s)
|
|
99
|
+
if "persistentVolumeClaim" in v:
|
|
100
|
+
pvc = v["persistentVolumeClaim"].get("claimName") if isinstance(v["persistentVolumeClaim"], dict) else None
|
|
101
|
+
if pvc:
|
|
102
|
+
t = by_kind.get(("PersistentVolumeClaim", ns, pvc))
|
|
103
|
+
if t:
|
|
104
|
+
g.add_edge(r, t, EdgeType.VOLUME_PVC, pvc)
|
|
105
|
+
|
|
106
|
+
# 3. containers: envFrom, env[].valueFrom
|
|
107
|
+
containers = spec.get("containers") or []
|
|
108
|
+
if isinstance(containers, list):
|
|
109
|
+
for c in containers:
|
|
110
|
+
if not isinstance(c, dict):
|
|
111
|
+
continue
|
|
112
|
+
for ef in c.get("envFrom") or []:
|
|
113
|
+
if isinstance(ef, dict):
|
|
114
|
+
if "configMapRef" in ef and isinstance(ef["configMapRef"], dict):
|
|
115
|
+
name = ef["configMapRef"].get("name")
|
|
116
|
+
if name:
|
|
117
|
+
t = by_kind.get(("ConfigMap", ns, name))
|
|
118
|
+
if t:
|
|
119
|
+
g.add_edge(r, t, EdgeType.ENV_FROM, name)
|
|
120
|
+
if "secretRef" in ef and isinstance(ef["secretRef"], dict):
|
|
121
|
+
name = ef["secretRef"].get("name")
|
|
122
|
+
if name:
|
|
123
|
+
t = by_kind.get(("Secret", ns, name))
|
|
124
|
+
if t:
|
|
125
|
+
g.add_edge(r, t, EdgeType.ENV_FROM, name)
|
|
126
|
+
for env in c.get("env") or []:
|
|
127
|
+
if not isinstance(env, dict):
|
|
128
|
+
continue
|
|
129
|
+
vf = env.get("valueFrom")
|
|
130
|
+
if not isinstance(vf, dict):
|
|
131
|
+
continue
|
|
132
|
+
if "configMapKeyRef" in vf and isinstance(vf["configMapKeyRef"], dict):
|
|
133
|
+
name = vf["configMapKeyRef"].get("name")
|
|
134
|
+
if name:
|
|
135
|
+
t = by_kind.get(("ConfigMap", ns, name))
|
|
136
|
+
if t:
|
|
137
|
+
g.add_edge(r, t, EdgeType.ENV_VALUE_FROM, name)
|
|
138
|
+
if "secretKeyRef" in vf and isinstance(vf["secretKeyRef"], dict):
|
|
139
|
+
name = vf["secretKeyRef"].get("name")
|
|
140
|
+
if name:
|
|
141
|
+
t = by_kind.get(("Secret", ns, name))
|
|
142
|
+
if t:
|
|
143
|
+
g.add_edge(r, t, EdgeType.ENV_VALUE_FROM, name)
|
|
144
|
+
|
|
145
|
+
# 4. Service -> workload через selector
|
|
146
|
+
if r.kind == "Service":
|
|
147
|
+
selector = (r.raw.get("spec") or {}).get("selector") or {}
|
|
148
|
+
if isinstance(selector, dict) and selector:
|
|
149
|
+
for candidate in resources:
|
|
150
|
+
if candidate.kind not in {"Deployment", "StatefulSet", "DaemonSet", "ReplicaSet"}:
|
|
151
|
+
continue
|
|
152
|
+
if candidate.namespace != ns:
|
|
153
|
+
continue
|
|
154
|
+
labels = ((candidate.raw.get("spec") or {}).get("template") or {}).get("metadata", {}).get("labels") or {}
|
|
155
|
+
if all(labels.get(k) == v for k, v in selector.items()):
|
|
156
|
+
g.add_edge(r, candidate, EdgeType.SERVICE_TARGET, str(selector))
|
|
157
|
+
|
|
158
|
+
# 5. Ingress -> Service
|
|
159
|
+
if r.kind == "Ingress":
|
|
160
|
+
spec_i = r.raw.get("spec") or {}
|
|
161
|
+
rules = spec_i.get("rules") or []
|
|
162
|
+
for rule in rules if isinstance(rules, list) else []:
|
|
163
|
+
http = (rule or {}).get("http") or {}
|
|
164
|
+
for p in (http.get("paths") or []):
|
|
165
|
+
backend = (p or {}).get("backend") or {}
|
|
166
|
+
svc_name = ((backend.get("service") or {}).get("name") or (backend.get("serviceName")))
|
|
167
|
+
if svc_name:
|
|
168
|
+
t = by_kind.get(("Service", ns, svc_name))
|
|
169
|
+
if t:
|
|
170
|
+
g.add_edge(r, t, EdgeType.INGRESS_BACKEND, svc_name)
|
|
171
|
+
|
|
172
|
+
return g
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from .base import Invariant
|
|
2
|
+
from .local import (
|
|
3
|
+
ImageLatestInvariant,
|
|
4
|
+
NamespaceInvariant,
|
|
5
|
+
ProbeInvariant,
|
|
6
|
+
ResourcesInvariant,
|
|
7
|
+
)
|
|
8
|
+
from .topology import (
|
|
9
|
+
NamespaceConsistencyInvariant,
|
|
10
|
+
PortConsistencyInvariant,
|
|
11
|
+
ReferenceExistenceInvariant,
|
|
12
|
+
ReplicaDirectionInvariant,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def default_invariants() -> list[Invariant]:
|
|
17
|
+
return [
|
|
18
|
+
ImageLatestInvariant(),
|
|
19
|
+
ResourcesInvariant(),
|
|
20
|
+
ProbeInvariant(),
|
|
21
|
+
NamespaceInvariant(),
|
|
22
|
+
PortConsistencyInvariant(),
|
|
23
|
+
ReferenceExistenceInvariant(),
|
|
24
|
+
ReplicaDirectionInvariant(),
|
|
25
|
+
NamespaceConsistencyInvariant(),
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
__all__ = ["Invariant", "default_invariants"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
from ..graph import DependencyGraph
|
|
6
|
+
from ..models import K8sResource, Violation
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Invariant(ABC):
|
|
10
|
+
id: str
|
|
11
|
+
description: str
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def check(self, resources: list[K8sResource], graph: DependencyGraph) -> list[Violation]:
|
|
15
|
+
...
|
|
16
|
+
|
|
17
|
+
def _v(self, severity, message, files=None, lines=None) -> Violation:
|
|
18
|
+
return Violation(
|
|
19
|
+
invariant_id=self.id,
|
|
20
|
+
severity=severity,
|
|
21
|
+
message=message,
|
|
22
|
+
files=files or [],
|
|
23
|
+
lines=lines or [],
|
|
24
|
+
)
|