sofe-server 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,2 @@
1
+ """SOFE Server — FinOps Policies as Code API."""
2
+ __version__ = "0.1.0"
sofe_server/app.py ADDED
@@ -0,0 +1,221 @@
1
+ from __future__ import annotations
2
+ import uuid
3
+ from datetime import datetime, timezone
4
+ from typing import Optional
5
+
6
+ from fastapi import FastAPI, Header, HTTPException
7
+ from pydantic import BaseModel
8
+
9
+ from sofe.loader import load_policies, validate_policies
10
+ from sofe.collectors import collect_all
11
+ from sofe.engine import evaluate, evaluate_architecture
12
+
13
+ app = FastAPI(
14
+ title="SOFE API",
15
+ version="0.1.0",
16
+ description="Stairway Open FinOps Engine — FinOps Policies as Code",
17
+ )
18
+
19
+ # --- Models ---
20
+
21
+ class EvaluateRequest(BaseModel):
22
+ policies_dir: str = "./policies"
23
+ profile: Optional[str] = None
24
+ resource_types: Optional[list[str]] = None
25
+ regions: Optional[list[str]] = None
26
+ fail_on: Optional[str] = None
27
+
28
+ class ValidateRequest(BaseModel):
29
+ policy_yaml: str
30
+
31
+ # --- Auth (optional) ---
32
+
33
+ def check_api_key(x_api_key: Optional[str] = Header(None)):
34
+ # Local mode: no key required. Hosted mode: validate key (future).
35
+ pass
36
+
37
+ # --- Routes ---
38
+
39
+ @app.get("/health")
40
+ async def health():
41
+ return {"status": "ok", "version": "0.1.0"}
42
+
43
+ @app.post("/evaluate")
44
+ async def evaluate_endpoint(req: EvaluateRequest):
45
+ policies = load_policies(req.policies_dir)
46
+ if not policies:
47
+ raise HTTPException(status_code=422, detail="No policies found")
48
+
49
+ resources = collect_all(
50
+ profile=req.profile,
51
+ resource_types=req.resource_types,
52
+ regions=req.regions,
53
+ )
54
+
55
+ # Architecture-aware evaluation (includes cross-resource analysis)
56
+ arch_result = evaluate_architecture(policies, resources)
57
+ findings = arch_result["findings"]
58
+ insights = arch_result["insights"]
59
+
60
+ severity_order = ["critical", "high", "medium", "low", "info"]
61
+ failed = False
62
+ if req.fail_on:
63
+ threshold_idx = severity_order.index(req.fail_on)
64
+ failed = any(
65
+ severity_order.index(f.severity.value) <= threshold_idx
66
+ for f in findings
67
+ )
68
+
69
+ total_savings = sum(f.estimated_savings or 0 for f in findings)
70
+
71
+ # Count resources by type for topology visualization + include IDs for BYaML generation
72
+ resources_by_type: dict[str, int] = {}
73
+ resources_detail: dict[str, list[dict]] = {}
74
+ for r in resources:
75
+ resources_by_type[r.resource_type] = resources_by_type.get(r.resource_type, 0) + 1
76
+ if r.resource_type not in resources_detail:
77
+ resources_detail[r.resource_type] = []
78
+ resources_detail[r.resource_type].append({
79
+ "resource_id": r.resource_id,
80
+ "region": r.region,
81
+ })
82
+
83
+ # Get remediation commands for each finding
84
+ from sofe.remediation.commands import get_remediation_commands
85
+
86
+ return {
87
+ "evaluation_id": str(uuid.uuid4()),
88
+ "timestamp": datetime.now(timezone.utc).isoformat(),
89
+ "policies_evaluated": len(policies),
90
+ "resources_scanned": len(resources),
91
+ "findings_count": len(findings),
92
+ "total_estimated_savings": total_savings,
93
+ "failed": failed,
94
+ "resources_by_type": resources_by_type,
95
+ "resources_detail": resources_detail,
96
+ "findings": [
97
+ {
98
+ "id": str(uuid.uuid4()),
99
+ "policy_name": f.policy_name,
100
+ "severity": f.severity.value,
101
+ "resource_id": f.resource_id,
102
+ "resource_type": f.resource_type,
103
+ "region": f.region,
104
+ "account_id": f.account_id,
105
+ "message": f.message,
106
+ "estimated_savings": f.estimated_savings,
107
+ "recommendation": f.recommendation,
108
+ "remediation_commands": get_remediation_commands(
109
+ f.policy_name, f.resource_id, f.resource_type, f.region, f.account_id or ""
110
+ ),
111
+ "timestamp": datetime.now(timezone.utc).isoformat(),
112
+ }
113
+ for f in findings
114
+ ],
115
+ "insights": {
116
+ "relationships_count": insights.get("relationships_count", 0),
117
+ "single_points_of_failure": insights.get("single_points_of_failure", []),
118
+ "blast_radius": insights.get("blast_radius", {}),
119
+ "team_costs": insights.get("team_costs", {}),
120
+ },
121
+ }
122
+
123
+ @app.post("/validate")
124
+ async def validate_endpoint(req: ValidateRequest):
125
+ import tempfile, os, yaml
126
+ # Write YAML to temp file, validate
127
+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False)
128
+ tmp.write(req.policy_yaml)
129
+ tmp.close()
130
+ try:
131
+ results = validate_policies(os.path.dirname(tmp.name), filename=os.path.basename(tmp.name))
132
+ r = results[0] if results else {"valid": False, "error": "No policy parsed"}
133
+ return {"valid": r.get("valid", False), "errors": [r.get("error", "")] if not r.get("valid") else []}
134
+ finally:
135
+ os.unlink(tmp.name)
136
+
137
+ @app.get("/policies")
138
+ async def list_policies(policies_dir: str = "./policies"):
139
+ policies = load_policies(policies_dir)
140
+ return [
141
+ {
142
+ "name": p.metadata.name,
143
+ "description": p.metadata.description,
144
+ "severity": p.spec.severity.value,
145
+ "resource_types": p.spec.scope.resource_types,
146
+ "metric": p.spec.rule.metric,
147
+ }
148
+ for p in policies
149
+ ]
150
+
151
+ @app.get("/metrics")
152
+ async def list_metrics():
153
+ return [
154
+ {"name": "avg_cpu_utilization", "source": "CloudWatch", "resource_types": ["aws.ec2", "aws.rds"], "description": "Average CPU % over period"},
155
+ {"name": "monthly_cost", "source": "Cost Explorer", "resource_types": ["*"], "description": "Monthly cost in USD"},
156
+ {"name": "running_days", "source": "LaunchTime", "resource_types": ["aws.ec2", "aws.rds"], "description": "Days since launch"},
157
+ {"name": "has_tag:{key}", "source": "Tags API", "resource_types": ["*"], "description": "1.0 if tag exists, 0.0 if missing"},
158
+ {"name": "invocations", "source": "CloudWatch", "resource_types": ["aws.lambda"], "description": "Total invocations over period"},
159
+ {"name": "connections", "source": "CloudWatch", "resource_types": ["aws.rds"], "description": "Active connections"},
160
+ {"name": "attached", "source": "EC2 API", "resource_types": ["aws.ebs"], "description": "1.0 if attached, 0.0 if not"},
161
+ ]
162
+
163
+
164
+ @app.get("/collectors")
165
+ async def list_collectors():
166
+ from sofe.collectors.aws import COLLECTORS
167
+ return [
168
+ {
169
+ "name": collector_cls.__name__.replace("Collector", ""),
170
+ "resource_type": resource_type,
171
+ "metrics": _get_collector_metrics(resource_type),
172
+ }
173
+ for resource_type, collector_cls in COLLECTORS.items()
174
+ ]
175
+
176
+ def _get_collector_metrics(resource_type: str) -> list[str]:
177
+ """Return known metrics for a resource type."""
178
+ metrics_map = {
179
+ "aws.ec2": ["avg_cpu_utilization", "monthly_cost", "running_days", "has_tag:*", "purchase_option_spot", "instance_generation_old", "ebs_optimized", "public_ip_attached"],
180
+ "aws.s3": ["monthly_cost", "encryption_enabled", "has_lifecycle_rules", "has_tag:*", "versioning_enabled", "public_access_blocked", "logging_enabled"],
181
+ "aws.lambda": ["monthly_cost", "has_tag:*", "memory_size_mb", "timeout_seconds", "runtime_deprecated", "code_size_mb"],
182
+ "aws.rds": ["avg_connections", "monthly_cost", "has_tag:*", "multi_az", "storage_encrypted", "backup_retention_days", "publicly_accessible"],
183
+ "aws.ebs": ["attached", "monthly_cost", "has_tag:*", "size_gb", "volume_type_gp2", "encrypted"],
184
+ "aws.ecs": ["avg_cpu_utilization", "has_tag:*", "running_count", "desired_count", "launch_type_fargate"],
185
+ "aws.eks": ["monthly_cost", "has_tag:*", "endpoint_public_access", "logging_enabled", "version_outdated"],
186
+ "aws.elasticache": ["monthly_cost", "at_rest_encryption", "transit_encryption", "num_nodes"],
187
+ "aws.redshift": ["monthly_cost", "encrypted", "publicly_accessible", "num_nodes"],
188
+ "aws.dynamodb": ["monthly_cost", "has_tag:*", "billing_mode_provisioned", "item_count", "table_size_mb"],
189
+ "aws.cloudfront": ["compression_enabled", "monthly_cost", "https_only", "waf_enabled", "price_class_all"],
190
+ "aws.apigateway": ["throttle_configured", "monthly_cost", "logging_enabled", "endpoint_type_edge"],
191
+ "aws.natgateway": ["monthly_cost", "connectivity_public"],
192
+ "aws.elb": ["has_targets", "monthly_cost", "waf_enabled", "internet_facing"],
193
+ "aws.route53": ["record_count", "private_zone"],
194
+ "aws.secretsmanager": ["rotation_enabled", "days_since_last_rotation", "days_since_last_access"],
195
+ "aws.sagemaker": ["monthly_cost", "instance_count", "endpoint_active"],
196
+ }
197
+ return metrics_map.get(resource_type, ["monthly_cost"])
198
+
199
+
200
+ @app.post("/connect/test")
201
+ async def test_connection(body: dict):
202
+ """Test STS AssumeRole — verifies the user's IAM role works."""
203
+ import boto3
204
+ role_arn = body.get("role_arn")
205
+ external_id = body.get("external_id")
206
+
207
+ if not role_arn or not external_id:
208
+ raise HTTPException(status_code=400, detail="role_arn and external_id required")
209
+
210
+ try:
211
+ sts = boto3.client("sts")
212
+ resp = sts.assume_role(
213
+ RoleArn=role_arn,
214
+ RoleSessionName="sofe-connect-test",
215
+ ExternalId=external_id,
216
+ DurationSeconds=900,
217
+ )
218
+ account_id = resp["AssumedRoleUser"]["Arn"].split(":")[4]
219
+ return {"success": True, "account_id": account_id}
220
+ except Exception as e:
221
+ raise HTTPException(status_code=400, detail=f"AssumeRole failed: {str(e)}")
sofe_server/main.py ADDED
@@ -0,0 +1,7 @@
1
+ import uvicorn
2
+
3
+ def run():
4
+ uvicorn.run("sofe_server.app:app", host="0.0.0.0", port=8080, reload=True)
5
+
6
+ if __name__ == "__main__":
7
+ run()
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: sofe-server
3
+ Version: 0.1.0
4
+ Summary: SOFE API Server — FinOps Policies as Code REST API
5
+ Author-email: Carlos Cortez <carlos@cortez.cloud>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: sofe>=0.2.0
11
+ Requires-Dist: fastapi>=0.111.0
12
+ Requires-Dist: uvicorn>=0.30.0
13
+ Requires-Dist: pydantic>=2.0
14
+ Dynamic: license-file
15
+
16
+ # 🟢 SOFE Server — FinOps Policy Engine API
17
+
18
+ REST API server for the [SOFE](https://sofe.dev) (Stairway Open FinOps Engine). Wraps the SOFE Python engine in a FastAPI application, enabling HTTP-based evaluations.
19
+
20
+ ## Quick Start
21
+
22
+ ```bash
23
+ pip install sofe sofe-server
24
+ sofe-server
25
+ # → http://localhost:8080
26
+ ```
27
+
28
+ Or use the Go CLI:
29
+ ```bash
30
+ sofe serve # starts sofe-server in background
31
+ sofe evaluate # calls localhost:8080/evaluate
32
+ ```
33
+
34
+ ## Endpoints
35
+
36
+ | Method | Path | Description |
37
+ |--------|------|-------------|
38
+ | GET | `/health` | Health check |
39
+ | POST | `/evaluate` | Evaluate AWS account against policies |
40
+ | POST | `/validate` | Validate a BYaML YAML file |
41
+ | GET | `/policies` | List all loaded policies |
42
+ | GET | `/collectors` | List available collectors |
43
+ | GET | `/metrics` | List metrics per collector |
44
+ | POST | `/connect/test` | Test STS AssumeRole connection |
45
+
46
+ ## Usage
47
+
48
+ ### Evaluate your AWS account
49
+
50
+ ```bash
51
+ curl -X POST http://localhost:8080/evaluate \
52
+ -H "Content-Type: application/json" \
53
+ -d '{"aws_profile": "default"}'
54
+ ```
55
+
56
+ ### With cross-account role
57
+
58
+ ```bash
59
+ curl -X POST http://localhost:8080/evaluate \
60
+ -H "Content-Type: application/json" \
61
+ -d '{
62
+ "role_arn": "arn:aws:iam::123456789012:role/SOFEReadOnlyRole",
63
+ "external_id": "sofe-abc123"
64
+ }'
65
+ ```
66
+
67
+ ### List policies
68
+
69
+ ```bash
70
+ curl http://localhost:8080/policies
71
+ ```
72
+
73
+ ## Docker
74
+
75
+ ```bash
76
+ docker run -p 8080:8080 -v ~/.aws:/root/.aws:ro \
77
+ ghcr.io/breakingthecloud/sofe-community:latest
78
+ ```
79
+
80
+ ## Architecture
81
+
82
+ ```
83
+ sofe-server (this repo)
84
+ │
85
+ │ imports
86
+ ▼
87
+ sofe/ (engine — pip install sofe)
88
+ │
89
+ │ boto3
90
+ ▼
91
+ Your AWS Account (read-only)
92
+ ```
93
+
94
+ sofe-server is a **thin wrapper** — all logic lives in the [sofe engine](https://github.com/breakingthecloud/sofe).
95
+
96
+ ## Requirements
97
+
98
+ - Python 3.11+
99
+ - `sofe` >= 0.2.0 (engine)
100
+ - AWS credentials (profile or role)
101
+
102
+ ## Development
103
+
104
+ ```bash
105
+ git clone https://github.com/breakingthecloud/sofe-server.git
106
+ cd sofe-server
107
+ uv venv && source .venv/bin/activate
108
+ uv pip install -e ".[dev]" -e ../sofe/
109
+ uvicorn sofe_server.app:app --reload --port 8080
110
+ ```
111
+
112
+ ## Related Projects
113
+
114
+ | Project | Description |
115
+ |---------|-------------|
116
+ | [sofe](https://github.com/breakingthecloud/sofe) | Python engine (collectors + policies) |
117
+ | [sofe-cli](https://github.com/breakingthecloud/sofe-cli) | Go CLI (19 commands, TUI) |
118
+ | [sofe-action](https://github.com/breakingthecloud/sofe-action) | GitHub Action for CI/CD |
119
+ | [platform.sofe.dev](https://platform.sofe.dev) | SaaS dashboard (free tier) |
120
+ | [sofe.dev/docs](https://sofe.dev/docs) | Documentation (26 pages) |
121
+
122
+ ## License
123
+
124
+ Apache 2.0 — see [LICENSE](LICENSE)
@@ -0,0 +1,9 @@
1
+ sofe_server/__init__.py,sha256=5Wj4AQg31P9uW5dH0Too6X2BdhwFcdrhKVURqp3_UUA,73
2
+ sofe_server/app.py,sha256=fAIFCWqyWTpp6RYKu18t_2a6MKoUtjk2HzKueK1F4zw,9527
3
+ sofe_server/main.py,sha256=VMEs0_9V4LTnxUGtb0XvalgHgdi6egMzPL6SBLHcIFI,144
4
+ sofe_server-0.1.0.dist-info/licenses/LICENSE,sha256=W42gOhs90g5sWk56eE-WZF4eGgKyPmKjBE2184yPKyA,4055
5
+ sofe_server-0.1.0.dist-info/METADATA,sha256=iuZrrhLWYDteUrgPTLBMeefMrYXQnr2Cbsfim5kD0b0,3076
6
+ sofe_server-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ sofe_server-0.1.0.dist-info/entry_points.txt,sha256=8zVqtm8_MPnWPF-9XJC1c1AQiS-9tdPJm2QHUp8CARc,53
8
+ sofe_server-0.1.0.dist-info/top_level.txt,sha256=sj9xH0-CWYvkXzSCwrMbm_JfCPlVnk-n91sWdYhCftQ,12
9
+ sofe_server-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sofe-server = sofe_server.main:run
@@ -0,0 +1,93 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity.
18
+
19
+ "You" (or "Your") shall mean an individual or Legal Entity
20
+ exercising permissions granted by this License.
21
+
22
+ "Source" form shall mean the preferred form for making modifications.
23
+
24
+ "Object" form shall mean any form resulting from mechanical
25
+ transformation or translation of a Source form.
26
+
27
+ "Work" shall mean the work of authorship made available under the License.
28
+
29
+ "Derivative Works" shall mean any work that is based on the Work.
30
+
31
+ "Contribution" shall mean any work of authorship submitted to the Licensor.
32
+
33
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of whom
34
+ a Contribution has been received by the Licensor.
35
+
36
+ 2. Grant of Copyright License. Subject to the terms and conditions of
37
+ this License, each Contributor hereby grants to You a perpetual,
38
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
39
+ copyright license to reproduce, prepare Derivative Works of,
40
+ publicly display, publicly perform, sublicense, and distribute the
41
+ Work and such Derivative Works in Source or Object form.
42
+
43
+ 3. Grant of Patent License. Subject to the terms and conditions of
44
+ this License, each Contributor hereby grants to You a perpetual,
45
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
46
+ patent license to make, have made, use, offer to sell, sell,
47
+ import, and otherwise transfer the Work.
48
+
49
+ 4. Redistribution. You may reproduce and distribute copies of the
50
+ Work or Derivative Works thereof in any medium, with or without
51
+ modifications, and in Source or Object form, provided that You
52
+ meet the following conditions:
53
+
54
+ (a) You must give any other recipients of the Work or
55
+ Derivative Works a copy of this License; and
56
+
57
+ (b) You must cause any modified files to carry prominent notices
58
+ stating that You changed the files; and
59
+
60
+ (c) You must retain, in the Source form of any Derivative Works
61
+ that You distribute, all copyright, patent, trademark, and
62
+ attribution notices from the Source form of the Work; and
63
+
64
+ (d) If the Work includes a "NOTICE" text file, You must include
65
+ a readable copy of the attribution notices contained within
66
+ such NOTICE file.
67
+
68
+ 5. Submission of Contributions.
69
+
70
+ 6. Trademarks. This License does not grant permission to use the trade
71
+ names, trademarks, service marks, or product names of the Licensor.
72
+
73
+ 7. Disclaimer of Warranty. The Work is provided on an "AS IS" BASIS,
74
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
75
+
76
+ 8. Limitation of Liability. In no event shall any Contributor be
77
+ liable to You for damages.
78
+
79
+ 9. Accepting Warranty or Additional Liability.
80
+
81
+ Copyright 2026 Carlos Cortez (FinOptix)
82
+
83
+ Licensed under the Apache License, Version 2.0 (the "License");
84
+ you may not use this file except in compliance with the License.
85
+ You may obtain a copy of the License at
86
+
87
+ http://www.apache.org/licenses/LICENSE-2.0
88
+
89
+ Unless required by applicable law or agreed to in writing, software
90
+ distributed under the License is distributed on an "AS IS" BASIS,
91
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
92
+ See the License for the specific language governing permissions and
93
+ limitations under the License.
@@ -0,0 +1 @@
1
+ sofe_server