Add keep_open_until to /allowed for hold-door; fix 9 bugs
/allowed returns keep_open_until from the newest approved hold in doorlog; /longpoll skips hold events to avoid spurious open pulses. Fixes: assert->raise for SECRET check, text() on 403, remove dead /logs code, flatten auth decorator, by_slackid None fallback, load kube config once, guard missing slack command, backoff on PyMongoError, mongo->mongosh.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
from datetime import date, datetime, timezone
|
||||
from datetime import datetime, timezone
|
||||
from functools import wraps
|
||||
from typing import List
|
||||
|
||||
@@ -24,8 +24,10 @@ DOORBOY_SECRET_WORKSHOP = os.environ["DOORBOY_SECRET_WORKSHOP"]
|
||||
|
||||
MONGO_URI = os.environ["MONGO_URI"]
|
||||
|
||||
assert len(DOORBOY_SECRET_FLOOR) >= 10
|
||||
assert len(DOORBOY_SECRET_WORKSHOP) >= 10
|
||||
if len(DOORBOY_SECRET_FLOOR) < 10:
|
||||
raise ValueError("DOORBOY_SECRET_FLOOR must be at least 10 characters")
|
||||
if len(DOORBOY_SECRET_WORKSHOP) < 10:
|
||||
raise ValueError("DOORBOY_SECRET_WORKSHOP must be at least 10 characters")
|
||||
|
||||
|
||||
@app.listener("before_server_start")
|
||||
@@ -35,19 +37,16 @@ async def setup_db(app):
|
||||
app.ctx.db = AsyncIOMotorClient(MONGO_URI).get_default_database()
|
||||
|
||||
|
||||
def authenticate_door(wrapped):
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
async def decorated_function(request, *args, **kwargs):
|
||||
doorboy_secret = request.headers.get("KEY")
|
||||
if doorboy_secret not in [DOORBOY_SECRET_FLOOR, DOORBOY_SECRET_WORKSHOP]:
|
||||
return text("Invalid doorboy secret token", status=401)
|
||||
def authenticate_door(f):
|
||||
@wraps(f)
|
||||
async def decorated_function(request, *args, **kwargs):
|
||||
doorboy_secret = request.headers.get("KEY")
|
||||
if doorboy_secret not in [DOORBOY_SECRET_FLOOR, DOORBOY_SECRET_WORKSHOP]:
|
||||
return text("Invalid doorboy secret token", status=401)
|
||||
|
||||
return await f(request, *args, **kwargs)
|
||||
return await f(request, *args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
return decorator(wrapped)
|
||||
return decorated_function
|
||||
|
||||
|
||||
# Door controllers query uid_hashes for offline use. There is no online uid_hash authn/z, only logging.
|
||||
@@ -64,7 +63,7 @@ async def view_doorboy_uids(request):
|
||||
users = kube.users_with_group("k-space:workshop")
|
||||
else:
|
||||
print("WARN: unknown door token in /allowed")
|
||||
return "unknown doorboy secret token", 403
|
||||
return text("unknown doorboy secret token", status=403)
|
||||
|
||||
flt = {
|
||||
"token.uid_hash": {"$exists": True},
|
||||
@@ -78,60 +77,38 @@ async def view_doorboy_uids(request):
|
||||
|
||||
doorname = request.headers.get("DOOR_NAME")
|
||||
print(f"delegating {len(tokens)} doorkey tokens to {doorname}")
|
||||
return json({"allowed_hashes": tokens})
|
||||
|
||||
# Determine which doors this key controls, then compute keep_open_until
|
||||
# for the requesting controller's door (newest active approved hold wins).
|
||||
if key == DOORBOY_SECRET_FLOOR:
|
||||
door_set = {"backdoor", "frontdoor", "grounddoor"}
|
||||
elif key == DOORBOY_SECRET_WORKSHOP:
|
||||
door_set = {"workshopdoor"}
|
||||
else:
|
||||
door_set = set()
|
||||
|
||||
def datetime_to_json_formatting(o):
|
||||
if isinstance(o, (date, datetime)):
|
||||
return o.isoformat()
|
||||
keep_open_until = None
|
||||
if doorname in door_set:
|
||||
hold = await request.app.ctx.db.doorlog.find_one(
|
||||
{"method": "hold", "door": doorname, "approved": True},
|
||||
sort=[("timestamp", -1)],
|
||||
)
|
||||
# DB datetimes are naive UTC; attach tzinfo only for the serialized
|
||||
# output per integration contract.
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
if hold and hold.get("expires") and hold["expires"] > now:
|
||||
keep_open_until = hold["expires"].replace(tzinfo=timezone.utc).isoformat()
|
||||
|
||||
return json({"allowed_hashes": tokens, "keep_open_until": keep_open_until})
|
||||
|
||||
|
||||
# Only identified and successful events. **Endpoint not in use.**
|
||||
# The query logic below is preserved as reference for future re-enablement;
|
||||
# see git history for the original implementation.
|
||||
@app.route("/logs")
|
||||
async def view_open_door_events(request):
|
||||
return text("not an admin"), 403
|
||||
|
||||
results = (
|
||||
await app.ctx.db.eventlog.find(
|
||||
{
|
||||
"component": "doorboy",
|
||||
"type": "open-door",
|
||||
"approved": True,
|
||||
"$or": [
|
||||
{"type": "open-door"},
|
||||
{"event": "card-swiped"},
|
||||
],
|
||||
"door": {"$exists": True},
|
||||
"timestamp": {"$exists": True},
|
||||
}
|
||||
)
|
||||
.sort("timestamp", -1)
|
||||
.to_list(length=None)
|
||||
)
|
||||
|
||||
transformed = []
|
||||
for r in results:
|
||||
if r.get("type") == "open-door" and r.get("approved") and r.get("method"):
|
||||
transformed.append(
|
||||
{
|
||||
"method": r.get("method"),
|
||||
"door": r["door"],
|
||||
"timestamp": r.get("timestamp"),
|
||||
"member": r.get("member"),
|
||||
}
|
||||
)
|
||||
if r.get("event") == "card-swiped" and r.get("success"):
|
||||
transformed.append(
|
||||
{
|
||||
"method": "card-swiped",
|
||||
"door": r["door"],
|
||||
"timestamp": r.get("timestamp"),
|
||||
"member": r.get("inventory", {}).get("owner"),
|
||||
}
|
||||
)
|
||||
|
||||
return json(transformed, default=datetime_to_json_formatting)
|
||||
|
||||
|
||||
# Door controllers listen for open events (web, slack).
|
||||
@app.route("/longpoll", stream=True)
|
||||
@@ -155,7 +132,9 @@ async def view_longpoll(request):
|
||||
continue
|
||||
if ev["method"] == "card":
|
||||
continue
|
||||
|
||||
if ev["method"] == "hold":
|
||||
continue
|
||||
|
||||
print("realtime opening %s" % ev["door"])
|
||||
await response.send("data: %s\n\n" % ev["door"])
|
||||
except PyMongoError as e:
|
||||
|
||||
Reference in New Issue
Block a user